Beans, beans, and more beans...what does what? - java-ee-6

I've recently been given a project to work on that involves writing a web application. I've never done Java EE before. A lot of resources on the web are dated and I'm having trouble figuring out what the current differences are between the various standards and Java technologies.
Originally I thought I really needed EJB 3.1 due to dependency injection, JPA, session management, and web services. I started experimenting with Glassfish but was told that we had to write the thing in Tomcat. So I've been trying to figure out what I need as well as what and how to put into Tomcat to get there. I've begun to question whether I even need EJB at all.
I want to use JFS, I think, for the MVC architecture. In learning about that I've run into both ManagedBeans and CDI, which according to some renders the former obsolete and also seems to provide all the dependency injection stuff I want to enable unit testing. I've also come to realize that I can get JPA outside of EJB in the form of Hibernate and maybe a few others. Additionally it seems that web services, which I don't know that I need anyway, come in the form of another standard I can't think of the name right now and this also can be installed independently.
My major issue here is session management and state. It seems to me that all which remains for EJB to do is provide #Stateless/#Stateful and #Local/#Remote. However, as I understand it, some of this is already exists in the form of session management in the servlet container...but I don't know how much or what the major differences are that I need to account for in order to decide if I need these things at all.
So my question is, what are the basic, essential differences that I need to know in order to decide if EJB is worth looking at or if I have enough in the form of other libraries and technologies? I've been all over google and Usenet and have not been able to find this information anywhere.
Just thought of another bit. As I understand it, the #Stateful bean annotation provides me thread-safe state saving. I'm probably not going to directly use threads, but I know Java does so behind the scenes a lot and suspect EE especially so. When I need to keep state I don't want to be dealing with threads if this already provides it.

ManagedBean
Java EE 6 has three different ways of defining beans that are managed in one way or another:
#javax.faces.bean.ManagedBean
JSF 2.0 introduced this annotation declaring managed beans in faces-config.xml. This annotation is used to access a bean from the Expression Language.
#javax.inject.Named
In an EE 6 container CDI this annotation is a built-in qualifier types to provide a name to a bean, making it accessible through EL.
#javax.annotation.ManagedBean
This annotation attempts to generalize JSF managed beans for use elsewhere in Java EE.
If you deploy in an EE 6 container (If you use Tomcat or another servlet container, you can also get CDI by adding the Weld jar to your web app), then there is really no reason to use #javax.faces.bean.ManagedBean. Just use #javax.inject.Namedand start taking advantage of CDI sevices.
CDI
One of the objectives of CDI specification is to bring together the Web tier and the transactional services, making easy for developers to use EJB along with JSF in web applications of the Java EE platform.
With CDI you have the following services among others : well-defined lifecycle contexts(influenced by seam 2 and conversation scope), Dependency injection, loose coupling facilities like interceptors, decorators and events and portable extensions, which allows third-party frameworks to integrate in the Java EE 6 environment like SEAM 3 extensions
Managed beans and EJB Services
First of all CDI applies to any managed bean. Some managed beans are EJBs. When we need to use the EJB services in a managed bean, we just add a #Stateless, #Stateful or #Singleton annotation. IMO they act as complementary technologies allowing you to have a flexible and gradual development just only adding some annotations.
So, when should we use a session bean instead of a plain managed bean?
When you need some EJB features that CDI is missing : declarative transactions, concurrency management, pooling, remote or web service invocation ,timers and asynchronous method invokation.
Of course you could also get all aspects using third party libraries - but this would introduce additional complexity to your project. In terms of functionality IMHO EJB are the place to implement :
Business logic, allowing you to have a cleaning separation of busniness logic and web tier logic (implemented by "JSF backing beans" which are CDI managed beans but no EJB)
Functionality which makes most sense for components which are entrypoints to the application (endpoints for remote invocations delivered via RMI or HTTP)
Finally if you need EJB services then you need an Aplication Server (eg. GlassFish or Jboss AS) if you only need CDI services you need a Servlet Container(e.g Tomcat) plus CDI libraries.

Do you need the features provided by EJBs, i.e. security and transaction management? If the answer is yes, EJBs might be a good option.
If the answer is no, and you only need dependency injection, CDI could then be a good option.
You can also get similar capabilities with other 3rd party products, like Spring (dependency injection, Spring security, etc), but deciding whether you use one (EJB) or the other (e.g. Spring) is in many of the cases a matter of previous skillset.
In my opinion, if there are no previous constraints, going Java spec compliant is a good investment.

I would suggest you to start with the CDI and proceed to the EJB's (which is really adding one annotation on top of your POJO) if the requirements needs them (just as it was told - transactionality, web services, JMX, timers, EJB asynchronous invocations).
It's quite reasonable to develop an application in which your entry point is an EJB which encompasses your call in the transaction and allows you to define multiple entry points. The EJB then invokes the CDI beans with the business logic in them.
It's also worth noticing that the TomEE is a certified Java EE 6 Web Profile developed on top of the Apache Tomcat.

Related

JPA in EJB container vs. Web container

Is there any documentation / articles identifying best practices / rules for when should one use JPA in an ejb container vs. when is it appropriate to use JPA in a web container?
At a high level - couple of things that I can think about is if we have JPA in WAR then the transactional code will need to be managed by the developer in UserTransactions and it cannot be reused by other modules or even the EJB in the same application.
I typically use JPA for either Java SE applications or in a Container. The SE application is really only playing around or doing database loads or setup. I have setup JPA in Tomcat, but I wasn't really pleased with the end result and felt there was some issues that couldn't really be resolved.
EDIT: That said, consider Spring/Hibernate runs in a servlet container under your HTTP server of choice, and seems to be a pretty popular and mature platform, but also quite vendor specific. It will do just about anything I can think of that a Java EE certified container will do and perhaps more.
I think your considerations come down to what kind of application you're building which, in turn, provides a lot of input about what database to use.

Java EE DAO without EJB

Is it possible to create a DAO in Java EE environment, which uses JPA, but does not need to be a Stateless bean? I am asking because I have a huge number of EJBs, just because I need a few #Resources in the DAOs, i.e. EntityManager and so on.
What would you recommend as a way to simplify DAOs in huge project, it seems to me that having a full EJB (instead of a simple object) for a DAO is eccessive.
DAOs are accessed both from other EJBs and from servlets.
It's possible, but not recommended, to inject an EntityManager into other types of beans (like e.g. CDI managed beans) along with a UserTransaction and then manually manage your transactions.
In Java EE 7, JTA 1.2 contributes CDI compatible extensions for declarative transactions just like EJBs have, but at the moment there's no final release of any Java EE 7 AS yet.
it seems to me that having a full EJB (instead of a simple object) for a DAO is excessive.
Why do you think that? A "full" EJB is probably more lightweight than any other alternative, and almost certainly more lightweight than any home cooked thing you can come up with based on an EntityManager.
Don't forget that EJB beans share their resources automatically and that injection points only get proxies. If you mainly use stateless EJB beans, those proxies are akin to URLs, and not the "real" beans. This makes stateless and local EJB beans incredibly lightweight to inject.
Meaning, if you have a given Service where you inject (say) 10 DAOs, that each have an injected EntityManager, and during a given call 3 DAOs are invoked then only 3 beans are actually used and only 1 EntityManager instance. It really is rather efficient.
You can implement DAO as POJO is you want. But the DAO needs an EntitManager which must come from somewhere. Either
you look it up in the POJO with InitialContext#lookup
you pass it in the constructor of the POJO
You must pay attention that InitialContext#lookup will work only if the parent EJB has declared a dependency to the entity manager, even if it doesn't use it.
Whether it's worth the trouble is a judgment call. Local EJB are very cheap, and having many EJB is not a problem for the app server. It's more a problem of understandability by developpers. (See this other answer of me)
Another question to ask is whether you really need the DAOs. With EJB 3, they become very thin layer of logic, and it's worth pondering the pros and cons

JBoss cdi-api uses

I was looking for some help on CDI APIs. I'm sorry if my question looks naive, I tried looking on net for some high level description on CDI APIs, but couldn't get it right.
The javadoc says:
Contexts and Dependency Injection (CDI) defines a set of complementary services that help improve the structure of application code.
My question is in EJB 3.X we already have Annotations for helping with DI and injecting resources like PersistenceContext and other kind of resources. So where exactly the CDI APIs will be helpful? In plain web-app/standalone Java programs using J2SE?
EJB 3.0 comes with dependency injection on resource- and EJB-level - which is pretty cool already :-)
What CDI does (and which is even cooler) - it lowers the barrier to dependency injection to so-called "managed beans" (JSR 316) - which (among others) defines the minimal set of preconditions a class needs to benefit from dependency injection. Just slightly simplifying, one can say that all classes in a CDI project are managed beans and therefore are eligable for DI.
To summarize what CDI brings over EJB 3.0 in terms of DI:
you don't need EJBs anymore, CDI basically works with POJOs. That's truly lightweight, because it allows you to use EJBs when you need EJB, not when you need DI.
DI turns stateful - different dependencies live in different scopes - something EJB 3.0 completely fails to deliver.
you can benefit from a typesafe and loosely coupled interceptor mechanism
you can benefit from a typesafe and loosely coupled mechanism
Have a look at the first chapter here, and you'll get the idea :-)
DI in Java EE5 allows you inject only resources like JDBC DataSource, JPA EntityManager, UserTransaction, Web Services, EJBs etc. All this resources was managed by container.
With EE6 and with CDI in particular you aren't restricted to inject only resources - you can inject everything (every bean). Look at annotations which come with CDI specification: #Inject, #Named, #Scope, #Singleton etc.
CDI give you features like events, decorators etc.
Look at this tutorial, it should help you to understand CDI: http://java.dzone.com/articles/cdi-di-p2

Frameworks for Layering reusable Architectures

My question is very simple, my intention is to generate a repository with your responses so it could serve to the community when selecting frameworks for developing enterprise general purpose applications.
This could apply very well for general purpose languages such as C++, C# or Java.
What Framework do you recommend for generating Layered Architectures?
Based on you experience why do you prefer the usage of some Framework versus your own architecture?
How long do you believe your selected Framework will stay as a preferred option in the software development industry?
This is indeed an overly general question, especially since there are so many interpretations of the very word framework, and within the world of frameworks many different kinds for different tasks. Nevertheless, I'll give it a shot for Java.
Java
Java EE
The default overall enterprise framework of Java is called Java EE. Java EE strongly emphasis a layered architecture. It's a quite large framework and learning every aspect of it can take some time. It supports several types of applications. Extremely small and simple ones may only use JSP files with some scriptlets, while larger ones may use much more.
Java EE doesn't really enforce you to use all parts of it, but you pick and choose what you like.
Top down it consists of the following parts:
Web layer
For the web layer Java EE primarily defines a component and MVC based Web Framework called JSF - JavaServer Faces. JSF utilizes an XML based view description language (templating language) called Facelets. Pages are created by defining templates and letting template clients provide content for them, including other facelets and finally placing components and general markup on them.
JSF provides a well defined life-cyle for doing all the things that every web app should do: converting request values, validating them, calling out to business logic (the model) and finally delegating to a (Facelets) view for rendering.
For a more elaborate description look up some of the articles by BalusC here, e.g. What are the main disadvantages of Java Server Faces 2.0?
Business layer
The business layer in the Java EE framework is represented by a light-weight business component framework called EJB - Enterprise JavaBeans. EJBs are supposed to contain the pure business logic of an application. Among others EJBs take care of transactions, concurrency and when needed remoting.
An ordinary Java class becomes an EJB by applying the #Stateless annotation. By default, every method of that bean is then automatically transactional. Meaning, if the method is called and no transaction is active one is started, otherwise one is joined. If needed this behavior can be tuned or even disabled. In the majority of cases transactions will be transparent to the programmer, but if needed there is an explicit API in Java EE to manage them manually. This is the JTA API - Java Transaction API.
Methods on an EJB can easily be made to execute asynchronous by using the #Asynchronous annotation.
Java EE explicitly supports layering via the concept of a separate module specifically for EJBs. This isolates those beans and prevents them from accessing their higher layer. See this Packaging EJB in JavaEE 6 WAR vs EAR for a more elaborate explanation.
Persistence layer
For persistence the Java EE framework comes with a standard ORM framework called JPA - Java Persistence API. This is based on annotating plain java classes with the #Entity annotation and a property or field on them with #Id. Optionally (if needed) further information can be specified via annotations on how objects and object relations map to a relational database.
JPA heavily emphasizes slim entities. This means the entities themselves are as much as possible POJOs that can be easily send to other layers and even remote clients. An entity in Java EE typically does not take care of its own persistence (i.e. it does not hold any references to DB connections and such). Instead, a separate class called the EntityManager is provided to work with entities.
The most convenient way of working with this EntityManager is from within an EJB bean, which makes obtaining an instance and the handling of transactions a breeze. However, using JPA in any other layer, even outside the framework (e.g. in Java SE) is supported as well.
These are the most important services related to the traditional layers in a typical enterprise app, but the Java EE framework supports a great many additional services. Some of which are:
Messaging
Messaging is directly supported in the Java EE framework via the JMS API - Java Messaging Service. This allows business code to send messages to so-called queues and topics. Various parts of the application or even remote applications can listen to such a queue or topic.
The EJB component framework even has a type of bean that is specifically tailored for messaging; the message driven bean which has a onMessage method that is automatically invoked when a new message for the queue or topic that the bean is listening to comes in.
Next to JMS, Java EE also provides an event-bus, which is a simple light-weight alternative to full blown messaging. This is provided via the CDI API, which is a comprehensive API that among others provides scopes for the web layer and takes care of dependency injections. Being a rather new API it currently partially overlaps with EJB and the so-called managed beans from JSF.
Remoting
Java EE provides a lot of options for remoting out of the box. EJBs can be exposed to external code willing and able to communicate via a binary protocol by merely letting them implement a remote interface.
If binary communication is not an option, Java EE also provides various web service implementations. This is done via among others JAX-WS (web services, soap) and JAX-RS (Rest).
Scheduling
For scheduling periodic or timed jobs, Java EE offers a simple timer API. This API supports CRON-like timers using natural language, as well as timers for delayed execution of code or follow up checks.
This part of Java EE is usable but as mentioned fairly basic.
There are quite some more things in Java EE, but I think this about covers the most important things.
Spring
An alternative enterprise framework for Java is Spring. This is a proprietary, though fully open source framework.
Just as the Java EE framework, the Spring framework contains a web framework (called Spring MVC), a business component framework (simply called Spring, or Core Spring Framework) and a web services stack (called Spring Web Services).
Although many parts of the Java EE framework can be used standalone, Spring puts more emphasis on building up your own stack than Java EE does.
The choice of Java EE vs Spring is often a religiously influenced one. Technically both frameworks offer a similar programming model and a comparable amount of features. Java EE may be seen as slightly more light-weight (emphasis convention over configuration) and having the benefit of type-safe injections, while Spring may offer more of those smaller convenience methods that developers often need.
Additionally Spring offers a more thoroughly and directly usable security API (called Spring Security), where Java EE leaves a lot of security details open to (third party) vendors.
To specifically answer the second question:
Developing your own framework gives you the burden of having to maintain it and educating new developers in using it.
The larger your framework becomes, the more time you have to devote specifically to it and the less time you thus have to solve your actual business problem. This is okay if your business problem is the framework, but otherwise it can become a bit of a problem, even for very large companies that can dedicate a group of people to such a framework.
If you're a smaller company (say ~15 developer max) this can really become a huge burden.
Additionally, if your own framework is the kind of framework that can take advantage of third party developments (e.g. third parties can develop components for JSF), then your own framework obviously won't be able to take advantage of that.
Unless of course you open source your own framework, but this will only significantly increase the burden of supporting it. Just dumping your source code on sourceforge does not really count. You will have to actively support it. All of a sudden your framework becomes their framework with maybe 'weird' feature requests and awkward error reports for environments that you have no personal interest in.
This also assumes that your framework will actually be used by external users. Unless it's really very, very, good and you put lots of energy in it, this will probably not happen if it's simply the umpteenth Java web- or ORM framework.
Obviously, some people have to take up the job of creating new frameworks, otherwise the industry just stagnates, but if your prime concern is your business problem I would really think twice of starting your own framework.
Very vague question, I'm not really sure it's ever a good idea to "write your own" at this point for a work project (unless writing your own, IS the project). If it's a learning exercise, fine, but otherwise go use one of the libraries written by people who have been doing it far longer. If you really want to get involved, read their code, try and contribute patches etc.
For .Net there is Sharp Architecture Which is a pretty popular framework for layered applications.
Here's some of the stuff I use (I don't use Sharp Architecture)
First, the infrastructure stuff
For Dependency Injection, I use StructureMap. I use it because it's way more robust and performant than anything I would or could write, and it's very well supported within the .Net community. It also sticks to being DI, and doesn't venture out into other things that I might want to use other libs for (AOP etc). The fluent configuration is fantastic (but many .Net DI Tools have that now)
For AOP, I use Linfu Dynamic Proxy. I know a lot of people that like the code weaver variety for performance reasons, but that's always seemed a bit like premature optimization to me.
For a DataMapper, I use AutoMapper. This is one where I'm on again off again. If you can do your mappings based just on convention, then great, I'll use it. Once I have to start tweaking the configuration to do special things.... to me that starts to get into the gray area where the code might be more clear with just some left=>right wrapped in a function.
Web/UI
Asp.Net MVC. Although to be quite honest, I'm having a falling out lately and may soon be moving to FubuMvc. Asp.Net MVC seems like it has split personalities in terms of API design (dynamic over here, static over there, using blocks to render forms, but System.Actions to render other things etc). Combine that with the fact that it's not really OSS (you can't submit a patch), and to me there's a compelling reason why the community should come up with something better that's OSS.
Persistence
NHibernate, Specifically Fluent NHibernate. Sure I'd love to write my own OR/M, but at the same time I'm certain that the hordes of developers who have worked on NHibernate are way smarter than me.
Services/Distribution etc
WCF for Synchronous calls
NServiceBus for Messaging and most async calls.
Most of this stuff is OSS, so how long will it be around, well, I would imagine a good long while.
This question doesn't work very well. Selecting frameworks is difficult, and very context specific. For each selection process you might end up with a simple shortlist and a simple list of questions to answer, but those lists do not transfer well to other selections.
The number of parameters and the parameter sensitivity influencing a decision is very large, and at enterprise level a lot of them are not technical.
Currently, there are no frameworks available that are ready to support these near-term enterprise needs:
the switch for most of the workforce from pc to tablet and phone;
the switch from web client and rdbms to p2p/disconnected based storage and distribution

Simplest way to use JPA with my GWT application

I'd like to create a simple Google Web Toolkit application which makes uses RPCs. For persistence, I'd like to use something like the Java Persistence API.
Does this mean I have to use an application server like Glassfish? or can I stick with a simple web container?
In terms of concrete libraries, how should I proceed? TopLink? Hibernate? ...
I believe the GWT RPC stuff is implemented as simple servlets. Assuming that, you totally can use JPA in a web container like Tomcat and don't need a full blown J2EE app server.
To do that, you will need to do a bit of manual setup to make access to the PersistenceContext simpler. Hibernate suggests using ThreadLocal, and I have an entry on my blog that details how I did that for Tomcat here
I would personally recommend Glassfish, as being more stable, better implemented and generally higher quality that Tomcat. I don't want to start a flame war (by saying that putting J2EE into Tomcat is like putting lipstick on a pig), but I will tell you how we deploy all of our applications:
We use Glassfish as the web container, TopLink as the persistence provider, generally connected to a MySQL 5 database. We use the JPA POJOs all the way from the EJB layer, through the web tier, and the GWT layer as well, via RPC. We also use Stripes and JSPs for all the presentation logic that doesn't require AJAX functionality. We've never had any problems with this approach, and have so far done at least 10 large-scale projects this way. It's the best architecture that we've had to date, and we've had a lot (tomcat, jboss, hibernate, struts, spring, etc, etc, etc).
You can user any container you like, i mean servlet and jpa containers.
The key point is that GWT doesn't suport jpa, so you have to use DTO design parten.
This will keep everything organized and you will not have problems with lazy loading.