Showing posts with label CDI. Show all posts
Showing posts with label CDI. Show all posts

Wednesday, March 21, 2012

JEE6: Who Needs Aspect-Oriented Programming?

In Java EE, there is rarely an obvious use case for AOP.

According to Wikipedia, aspectoriented programming aims to separate reusable functionality from the business logic:

“In computing, aspectoriented programming (AOP) is a programming paradigm which aims to increase modularity by allowing the separation of cross-cutting concerns. AOP forms a basis for aspect-oriented software development.”
AOP was a hot topic a few years ago, but it never really took off in J2EE—and for good reason.

Aspects Are Commodities The integral parts of the Enterprise JavaBeans (EJB) 1.0 specification (JSR 318) in early 1998 were aspects. The developer had to develop the Bean class and the Remote and Home interfaces but none of the cross-cutting aspects. Threading, pooling, security, transactions, session handling, and even persistence were configurable aspects cleanly separated from the business logic.

The cross-cutting functionality was configurable in the early EJB 1.0 days with POJOs.

With the advent of EJB 1.1 and J2EE, Java classes were replaced with XML, and the recent Java EE 5 and Java EE 6 specifications made XML optional. You can configure the vast majority of all use cases with annotations and override them with XML.

Although the whole EJB 1.0 idea was based on aspects, you will find only two mentions of the word aspect in the original specification in different contexts.

AOP and EJB 1.0 were “invented” nearly at the same time.

In J2EE, the configurable decoration of an EJB bean with, for example, transactions was just an integral part of the development experience. Other frameworks
provided the same functionality but called that functionality AOP.

You will have a number of aspects by defining a simple EJB 3.1 bean. For example, a stateless EJB 3.1 bean comes with transaction and lifecycle aspects out of the box.

The method greet() is never invoked directly. The container dispatches the invocations to free EJB instances from the pool. Also, transactions are started before each method invocation.

The method call is processed by a chain of default and configurable aspects until it reaches the actual business logic. Outside the application server, you would probably implement the same functionality with the decorator pattern or with a more generic solution, such as AOP.

* For complete article by Adam Bien in Java Magazine check it out here

Saturday, March 3, 2012

JPA: 2 ways to get container-managed EntityManager in servlet

In Thread-safety when injecting EntityManager post, I wrote about the danger of using field/setter injection to get EntityManager in servlets and compares container-managed EntityManager vs application-managed EntityManager.

What if I need a container-managed EntityManager in my servlet class?
There are 2 ways to do that:

1. type-level injection + JNDI lookup

2. web.xml + JNDI lookup

The persistence-context-ref is declared in web.xml:


Friday, March 2, 2012

JPA: Thread-safety when injecting EntityManager

As I wrote in post Why we need type-level injections in JavaEE, injecting EJB 3 stateful beans into servlet instance fields is not thread-safe. Along the same line, injecting EntityManager with @PersistenceContext into servlet instance variables is not thread-safe, either. EntityManager is just not designed to be thread-safe.

For example, the following code snippet of a servlet class is incorrect:


One way to fix this is to inject EntityManagerFactory instead. EntityManagerFactory is guaranteed to be thread-safe. For example:

Continuing container-managed EntityManager vs application-managed EntityManager.

There are important differences between the injected EntityManager, and the EntityManager created from an injected EntityManagerFactory. Basically, injected EntityManager is container-managed, meaning all of its lifecycle is controlled by the container (web container or EJB container). Application code cannot close it, or otherwise interfere with its life.

In addition, for a container-managed EntityManager, its associated PersistenceContext is automatically propagated along with the underlying JTA, from servlet A to servlet B, from servlet to EJB, from EJB a to EJB B, and so on. As such, EntityManager of the same configuration injected into various classes can share the same PersistenceContext in a call stack.

On the other hand, EntityManager created from EntityManagerFactory is application-managed EntityManager. Application code is responsible for managing its whole lifecycle. And there is no PersistenceContext propagation for application-managed EntityManager.

Are all EntityManager's obtained from EntityManagerFactory application-managed EntityManager? Yes.

Is it possible to get a container-managed EntityManager from EntityManagerFactory? No.

You may have read about the method EntityManagerFactory.getEntityManager(), which returns a container-managed EntityManager. This method was considered and included in the early draft version of Java Persistence API, but was eventually removed from its final release.

JPA: Why we need to specifies the type-level injections in JavaEE?

As I wrote in the Injection level-types in JavaEE5+, JavaEE type-level injection is more verbose than field and setter injections. So why don't we just all use the simple field or setter injections? Well, there are sometimes a type-level injection is more appropriate

1. You want to lazily initialize a field such as a data source or bean. Having the container to initialize a field via field injection or setter injection has its overhead. With type-level injection, you have the resource and EJB reference fully configured without descriptors, but defer the actual initialization. Whenever you need the resource, just look it up.

Type-level injection also works well if you want to reference the injected resource in some non-component utility classes that are in the same naming context. Since only JavaEE component classes can take injections, you can't inject into POJO utility classes. For example, you can



The above example will also if we instead use field or setter injection. But the instance filed in FooServlet class that takes the injection may not be used at all. Another approach is to pass the data source reference injected into FooServlet as method parameters to ServletHelper. But it pollutes the API. It appears more natural, at least to me, to use type-level injection in this case.

2. You want to restrict the scope or sharing of the variable that references the resource. Field and setter injections both use instance variables, which are accessible to all methods and all threads of the current component instance. Instance variables represent shared states. With type-level injections, you typically assign the resource to a local variable and thus is thread-safe.

This is the reason why you shouldn't inject an EJB 3 stateful session bean into a servlet class variable. In so doing, this stateful bean variable will be shared by all request-processing threads running inside the servlet's service method. Servlet is stateless, so it should not keep state (the stateful session bean reference).


JPA: Injection level-types in JavaEE5+

There are 3 types of resource injections in JavaEE in the order of usage frequency:
  1. Field injection.
  2. Setter injection.
  3. Type-level injection. 
Unlike field and setter injections, type-level injections are not really injection. It does not inject anything into anywhere; it just declares a resource reference in a descriptor-free manner.

To use resource injected at type-level, you will need to do a traditional JNDI lookup. What we have saved here, compared to pre-JavaEE-5, is there is no need for deployment descriptors.

A servlet example in glassfish:


Type-level injections are inherently verbose, compared to field and setter injections, where a bare @EJB or @Resource is sufficient in some cases. Field and setter injections can use the field type and parameter type to infer the resource type, respectively.

Type-level injections can't. All the necessary attributes must be present.

  • For @Resource, you must specify at least name and type. 
  • For @EJB, you must have at least beanInterface and name.

Thursday, March 1, 2012

App. Server: GlassFish 3.1.2 Released

Oracle GlassFish Server 3.1.2 has just been released and is ready to download.

Oracle GlassFish Server 3.1.2 improves upon its ease-of use features, flexibility and improved developer productivity with several enhancements. Do you want an application server that's both state-of-the-art and production-ready? Johan Vos, CTO at LodgON, says GlassFish is his favorite application server because: 

"GlassFish contains the most advanced, state-of-the art technology that is seen in similar products a few years later and the quality of GlassFish is very high, the software is ready to be used in production."
Here are the highlights of the Oracle GlassFish Server 3.1.2 release:
  • Improved console startup time over previous versions of Oracle GlassFish Server.
  • Enhanced configuration of Java Message Service (JMS) clusters for fault tolerance and failover capabilities.
  • Easier Load Balancer configuration for faster throughput and reduced latenc.
  • Enhanced security with SSL Encrypted traffic between the Domain Administration Server and remote instances.

  • Support for the WebSocket Protocol RFC 6445, enabling bi-directional communication between a client and server, adding a web-origin based security model for browsers
.
  • New DCOM support. Windows users now have the flexibility to administer Glassfish clusters and instances remotely using SSH or DCOM.

  • New Support for non-Multicast clustering. GlassFish High-Availability clustering is now possible in environments where multicast is disabled.

  • Improved EclipseLink integration to enable data binding with JAX-WS. EclipseLink integration provides TopLink Grid support for using Coherence as a 2nd level data cache.
Learn the differences between Oracle GlassFish Server and GlassFish Server Open Source Edition at glassfish.java.net.

You can download GlassFish 3.1.2 from the Oracle Technology Network.

Sunday, February 12, 2012

Glassfish: How to create lookups resources (simple & JavaBean Object)

It is a good idea to make your code modular and maintainable (less code modifications) when depending on resources.

To create a resource in application server so that all deployed applications can look them up, and make your application is loosely coupled on the resource it lookups, and be more dynamic.

The resource types can be object, string, boolean, number, or any custom java bean types.

In Glassfish 3+ CLI (Command Line Interface), they are created and managed with a set of generic commands:

asadmin create-custom-resource ...
asadmin list-custom-resources ...
asadmin delete-custom-resource ...
asadmin get 'resources.custom-resource.*'
asadmin set ...


GlassFish admin console provides GUI (Graphical User Interface) way of doing things but I found using CLI (Command line Interface) is a lot faster.

Saturday, February 11, 2012

JEE7: Looking ahead to a new era

Get educated about Java EE 7 JSRs.
With the release of Java EE 7 scheduled for the second half of 2012, projected JSRs are all up and running. The Java EE 7 release, which will reflect the evolving needs of the industry as it moves into the cloud, is date driven: anything not ready will be deferred to Java EE 8.

Here is an update and summary of the key features of different specifications in the Java EE 7 platform.

Saturday, January 21, 2012

JEE6: Interfaces on Demand with EE6 (CDI & ejb3.1)

Interfaces are no longer required with Java EE 6, so you can use them more consciously for the realization of business logic.

Introduction
Since Java Platform, Enterprise Edition 6 (Java EE 6), interfaces are no longer required by the container in order to realize common use cases. Transactions, security, custom aspects, concurrency, and monitoring are also available for plain classes without any interfaces. Java EE 6 made interfaces meaningful again. Since they are no longer required by the platform, you can use them more consciously for the realization of business logic. An interface becomes a vehicle for encapsulation or abstraction, as it was originally intended to be:
“Interfaces are used to encode similarities which the classes of various types share, but do not necessarily constitute a class relationship. For instance, a human and a parrot can both whistle; however, it would not make sense to represent Humans and Parrots as subclasses of a Whistler class. Rather they would most likely be subclasses of an Animal class (likely with intermediate classes), but both would implement the Whistler interface.” [http://en.wikipedia.org/wiki/Java_interface]

Unfortunately, interfaces are not used within the context of Java EE as a tool for encoding similarities; they serve as reassurance for possible, but unlikely, future enhancements. Extensive use of interfaces derives from a belief that they might be helpful in the future.

Friday, January 20, 2012

JEE6: Part 3- The Java EE 6 Platform introduction

Part 1 | Part 2 | Part 3

EJB Technology, Even Easier to Use
Enterprise JavaBeans technology is the server-side component architecture for developing and deploying business applications in Java EE. Applications that you write using EJB technology are scalable, transactional, and secure. EJB 3.0, which is part of the Java EE 5 platform, made the technology a lot easier to use. Description:

The latest release of the technology, JSR 318: Enterprise JavaBeans 3.1, which is available in the Java EE 6 platform, further simplifies the technology and makes many improvements that reflect common usage patterns.

Some improvements made in EJB 3.1 are as follows:
  •  No-interface view. Allows you to specify an enterprise bean using only a bean class without having to write a separate business interface.
  • Singletons. Let's you easily share state between multiple instances of an enterprise bean component or between multiple enterprise bean components in an application.
  •  Asynchronous session bean invocation. Enables you to invoke session bean methods asynchronously by specifying an annotation.
  •  Simplified Packaging. Removes the restriction that enterprise bean classes must be packaged in an ejb-jar file. You can now place EJB classes directly in a WAR file.
  • EJB Lite. Is a subset of EJB 3.1 for inclusion in a variety of Java EE profiles.

JEE6: Part 2- The Java EE 6 Platform introduction

Part 1 | Part 2 | Part 3

Enhanced Web Tier Capabilities
Some of the most significant enhancements made in Java EE 6 appear in the web tier. As mentioned earlier, one of the goals of Java EE 6 is to make the platform more extensible, and two key improvements in the area of extensibility are web fragments and shared framework pluggability. These two new features are provided in Java EE 6 by Servlet 3.0 technology. Servlet 3.0, JSR 315, the latest version of Servlet technology, offers some other valuable enhancements such as support for asynchronous processing and support for annotations.

Another important Java EE 6 web tier technology is JSF 2.0, the latest version of JSF technology. Among its benefits, JSF 2.0 simplifies page and component authoring through Facelets, and adds support for asynchronous JavaScript and XML (commonly referred to as Ajax), and annotations.

Saturday, January 14, 2012

JEE6: Part 1- The Java EE 6 Platform introduction

Part 1 | Part 2 | Part 3

Java Platform, Enterprise Edition (Java EE) is the industry-standard platform for building enterprise-class applications coded in the Java programming language. Based on the solid foundation of Java Platform, Standard Edition (Java SE), Java EE adds libraries and system services that support the scalability, accessibility, security, integrity, and other requirements of enterprise-class applications.

Since its initial release in 1999, Java EE has matured into a functionally rich, high performance platform. Recent releases of the platform have also stressed simplicity and ease of use. In fact, with the current release of the platform, Java EE 5, development of Java enterprise applications has never been easier or faster.

Java EE 6 adds significant new technologies and extends the usability improvements made in previous Java EE releases.
Progress continues. The next release of the platform, Java EE 6, adds significant new technologies, some of which have been inspired by the vibrant Java EE community. It also further simplifies the platform, extending the usability improvements made in previous Java EE releases.


This article highlights some of the significant enhancements in Java EE 6; it consists of three parts Part 1, 2 and 3.

Sunday, January 8, 2012

JEE6: Observer pattern/Event implementation

Java Enterprise edition jee6 Observer pattern/Event implementation using CDI (JSR-299/JSR-330) and EJB3.1

In few steps you will create the pattern as the following.

1. You will have to define an event class first. It can be any POJO you like:

public class HelloEvent {
    private String message;
    public HelloEvent(String message) {
        this.message = message;
    }
    public String getMessage() {
        return message;
    }
}
2. An event has to be fired by an injected javax.enterprise.event.Event class. It can be injected into an EJB 3.1:
@Named("messenger")
@Stateless
public class HelloMessenger {
    @Inject Event<HelloEvent> events;
    public void hello(){
        events.fire(new HelloEvent("from bean " + System.currentTimeMillis()));
    }
}
3. The event can be consumed by another Session Bean / managed bean. You only have to use the @Observes annotation:

@Stateless
public class HelloListener {
    public void listenToHello(@Observes HelloEvent helloEvent){
        System.out.println("HelloEvent: " + helloEvent);
    }
}
4. You can access the EJB 3.1 directly - without any backing beans. You only have to use the name (messenger) from the @Named annotation in the JSF 2.0 page and bind the action to the method (hello()) name:
    <h:body>
        <h:form>
            <h:commandButton value="Fire!" action="#{messenger.hello}"/>
        </h:form>
  <h:body>

The project (Jee6ObsorverEvents) was implemented in few minutes with NetBeans 7.1, tested with Glassfish v3.1.1


JEE6: Is war package is the new ear ?

The pragmatic way of modularization and packaging...

It is not only possible to put EJBs and JSR-299 Beans together directly into a WAR - EJBs can be also packaged separately into a JAR. After copying the “ejb-jar” into the [WAR]/WEB-INF/lib folder, the included beans become automatically available to the web app.

No additional configuration or tweaking is required. In the contrary to the the old EAR packaging, all the classes are loaded with the same classloader. There is no difference between packaging the beans in a standalone JAR, or putting the byte code directly into the WEB-INF/classes folder.

You could even sprinkle the beans in as many JARs as you like - the Dependency Injection between them will just work. Because all the JARs inside the WEB-INF/lib are loaded by exactly the same classloader - it just behaves like a single JAR.

The new Java EE 6 WAR-packaging is interesting for the majority of the “business” projects with “weak” requirements regarding the modularization. You can partition your software into dependent pieces, without paying the costs of true JAR-isolation.

The EAR packaging is still interesting for projects with higher modularization requirements - here the EJB-JARs will be loaded with an isolated classloader separately. In the majority of all cases it is just an overhead: it is unlikely, that someone will replace a single EJB-JAR without rebuilding and testing the whole EAR...

from Adam Bien's blog

Saturday, June 18, 2011

EJB3: Learn Interceptors (EJB3) for absolute beginner or Aspect oriented programming in 2 minutes

I would like to explain the essence of interception and so realization of cross-cutting aspects.

Requirements:
  1. Installled JDK 1.5 (better 1.6) 
  2. An IDE of your choice e.g. vi, emacs, netbeans 6.1/6.5 (SE or EE), Eclipse Ganymede (SE or EE)
  3. @Stateless, @Local Annotations in classpath 
  4. An Java EE 5 capable application server of your choice. It will work with Glassfish v1+ (better v2), JBoss 4.2+, WLS 10+ and Geronimo
What is to do:
  1. Create and deploy a simple Stateless or Stateful Session Bean.
  2. Create a simple Java class with one method with the following signature:  public Object <any name you like>(InvocationContext context) throws Exception:

    import javax.interceptor.AroundInvoke;
    import javax.interceptor.InvocationContext;
    public class TracingInterceptor {
       
        @AroundInvoke
        public Object logCall(InvocationContext context) throws Exception {
            System.out.println("Invoking method: " + context.getMethod());
            return context.proceed();
        }
    }
  3. The method has to be annotated with  @AroundInvoke. It is the one and only available annotation.
  4. Inside the method you can "decorate" existing functionality. The invocation context.proceed() invokes the actual method and returns the value. An interceptor wraps the method completely.
  5. Apply the interceptor on any Session Bean you like e.g.:

    @Interceptors(TracingInterceptor.class)@Stateless
    public class HelloWorldBean implements HelloWorld {
        
         public void sayHello() {
            System.out.println("Hello!");
        }
    }
  6. The annotation @Interceptors can be applied for the whole class, or chosen methods. You can even exclude interceptors with @ExcludeClassInterceptors - but it is rarely needed.
  7. Compile everything and JAR the output (in Netbeans just "build", in Eclipse "Export -> JAR")
  8. Copy the JAR into the autodeploy folder of WLS 10 (bea10\user_projects\domains\YOUR_DOMAIN\autodeploy), or glassfish\domains\domain1\autodeploy in the case of Glassfish v2, or jboss-4.2.2.GA\server\default\deploy in case of JBoss
  9. Inspect the log files, you are done :-)
What you have gained:
  1. There is no XML needed - its DRY.
  2. Its robust - compiler checks for the existence of the Interceptor and checks the right spelling of the annotation etc.
  3. Cross cutting functionality can be easily factored out into reusable interceptors.
  4. DI works in interceptors. You can easily inject resources or other beans into an interceptor.
  5. The whole method is wrapped - you have full access to the parameters and return values. You can even reexcute the method or not do it at all (for caching purposes).
  6. It's self documented: there is no surprise - the annotation is visible in code.
  7. They are portable and run on every Java EE 5 compliant application server.
  8. No additional frameworks, libraries etc. are need. This is good for maintenance.
  9. Its flexible - if you prefer XML - no problem just configure the decoration in a XML-descriptor:
    <ejb-jar xmlns = "http://java.sun.com/xml/ns/javaee"
             version = "3.0"
             xmlns:xsi = "http://www.w3.org/2001/XMLSchema-instance"
             xsi:schemaLocation = "http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/ejb-jar_3_0.xsd">
        <interceptors>
            <interceptor>
                <interceptor-class>com.taman.logging.interceptor.TracingInterceptor</interceptor-class>
            </interceptor>
        </interceptors>
        <assembly-descriptor>
            <interceptor-binding>
                <ejb-name>HelloWorldBean</ejb-name>
                <interceptor-order>
                    <interceptor-class>com.taman.logging.interceptor.TracingInterceptor</interceptor-class>
                </interceptor-order>
            </interceptor-binding>
        </assembly-descriptor>
        </ejb-jar>

Interceptors and EJBs seem to be controversial. Interceptors are absolutely sufficient for the most use cases.

Friday, June 17, 2011

JEE 6: Simplicity by Design

Leverage new Java EE 6 features to build simple and maintainable applications.
The introduction of Java Platform, Enterprise Edition (Java EE) 5, in 2006, did a lot to simplify enterprise application development. Java EE 6, released in 2009, simplifies design and architecture tasks even further. Java EE 6 is a good choice for building small situational applications quickly and without any overhead. This article discusses various Java EE 6 architectures and design approaches that help developers build efficient, simple, and maintainable apps.
Java EE 6 consists of a set of independent APIs released together under the Java EE name. Although these APIs are independent, they fit together surprisingly well. For a given application, you could use only JavaServer Faces (JSF) 2.0, you could use Enterprise JavaBeans (EJB) 3.1 for transactional services, or you could use Contexts and Dependency Injection (CDI) with Java Persistence API (JPA) 2.0 and the Bean Validation model to implement transactions.
With a pragmatic mix of available Java EE 6 APIs, you can entirely eliminate the need to implement infrastructure services such as transactions, threading, throttling, or monitoring in your application. The real challenge is in selecting the right subset of APIs that minimizes overhead and complexity while making sure you don’t have to reinvent the wheel with custom code. As a general rule, you should strive to use existing Java SE and Java EE services before expanding your search to find alternatives. 

CDI: The Standard Glue

CDI, introduced with Java EE 6 to act as a glue for the different parts of the Java EE 6 specification, manages the lifecycle of POJO (Plain Old Java Object) beans and uses a type-safe mechanism for dependency injection. CDI also introduces many powerful features such as events, interceptors, decorators, standardized extension points, and the service provider interface. 
Because CDI is new and designed to be an integration layer, there is some overlap with older technologies. Although you can continue to use EJB 3.1 injection or JSF managed beans directly, you should consider using CDI wherever possible. CDI is more powerful, and you can simplify your application by using a single API.
CDI uses annotations to perform dependency injection. The most important annotation is javax.inject.Inject. The example in Listing 1 shows how this annotation can be used to inject a POJO into a servlet. All you need to do is to declare a field and annotate it with @Inject. When that code is executed, the container automatically initializes fields annotated with the @Inject annotation before the execution of any business methods.
Code Listing 1: POJO injection into a servlet with @Inject 
@WebServlet(name="HelloWorldService", urlPatterns={"/HelloWorldService"})
public class HelloWorldHTTPService extends HttpServlet {
   
    @Inject
    private Hello hello;
    
    @Override
    protected void doGet(HttpServletRequest request, HttpServletResponse response)
    throws ServletException, IOException {
        PrintWriter out = response.getWriter();
        out.println(hello.helloWorld());
        out.flush();
        out.close();
    } 
}

There are no specific requirements for the injected class, beyond having to contain a default constructor: 
public class Hello {
    public String helloWorld(){
        return "Hello World";
    }
}

To make the above example work, you would also need an empty beans.xml deployment descriptor with the following content: <beans></beans>. The existence of this configuration file in the WEB-INF folder activates CDI capabilities.
Note that the Hello class is a POJO and not an EJB. It doesn’t have to be declared or configured—the @Inject annotation ensures proper creation and lifecycle management. In the real world, you would rarely inject POJOs into a servlet; you would probably use a UI framework (such as JSF 2) or expose your service via representational state transfer (REST). In such cases, the use of CDI is even more beneficial.
To illustrate, consider a simple MessageMe application that stores a message string in a database. The JSF 2 markup consists of two components: inputText and commandButton. As shown in Listing 2, inputText is value-bound to a class with the name index with a property message, which has, in turn, a content attribute. commandButtons’s action attribute is bound to the save method of the backing bean with the name index.
Code Listing 2: index.xhtml: binding the values to a CDI backing bean 
<h:body>
     <h:form>
     Content:<h:inputText value="#{index.message.content}"/>
      <br/>
     <h:commandButton value="Save" action="#{index.save}"/>
     </h:form>
</h:body>

Listing 3 shows the backing bean implemented as a request-scoped CDI bean, using the @RequestScoped annotation for request handling. A JSF 2 managed bean (using the @ManagedBean annotation) could also work, but CDI is just as powerful. And using CDI everywhere simplifies the architecture, with a single glue API across all application layers.
Code Listing 3: A CDI backing bean with injected EJB 
package com.tm.messageme.presentation;
import com.tm.messageme.business.messaging.boundary.Messaging;
import com.tm.messageme.business.messaging.entity.Message;
import javax.enterprise.context.RequestScoped;
import javax.inject.Inject;
import javax.inject.Named;
@Named
@RequestScoped
public class Index {
    @Inject
    Messaging ms;
    private Message message = new Message();
    public Message getMessage() {
        return message;
    }
    public void save(){
        ms.store(message);
    }
}

The annotation @Named (as specified in the JSR 330 specification and implemented in Guice and Spring) makes the index backing bean visible in all expression language (EL) markup. It works according to the “convention over configuration” principle: the name of the backing bean in JSF 2 is derived from the class name. The first letter is not capitalized.
The Message class is implemented as a JPA 2 entity, as shown in Listing 4.
Code Listing 4: JPA 2 entity validated with Bean Validation 
package com.tm.messageme.business.messaging.entity;
@Entity
public class Message {
    @Id
    @GeneratedValue
    private Long id;
    @Size(min=2,max=140)
    private String content;

    public Message(String content) {
        this.content = content;
    }
    public Message() { /*required by JPA */}
    public String getContent() {
        return content;
    }
    public void setContent(String content) {
        this.content = content;
    }
    public Long getId() {
        return id;
    }
}

The next class in this example is the Messaging class, which is implemented as an EJB 3.1 session bean. This class represents a pragmatic exception to the “CDI everywhere” rule. EJBs provide many capabilities, such as transactions, pooling, Java Management Extensions (JMX) monitoring, and asynchronous execution—all for the price of a single additional @Stateless annotation. In future Java EE releases, these aspects are likely to be extracted from EJBs and made available in CDI as well. In Java EE 6, however, a boundary or facade of a business component is most effectively implemented as a stateless session bean.
The @Asynchronous annotation in Listing 5 is particularly interesting. It enables the asynchronous but transactional execution of methods and is available only for EJBs. Note that the Messaging EJB is injected with @Inject and not @EJB. In practice, either annotation would work, with virtually no difference. The use of @Inject is slightly more powerful and supports inheritance. The @EJB annotation, on the other hand, works only with EJBs.
Code Listing 5: A boundary implemented as an EJB session bean 
package com.tm.messageme.business.messaging.boundary;
import com.tm.messageme.business.messaging.control.MessageStore;
import com.tm.messageme.business.messaging.entity.Message;
import javax.ejb.Asynchronous;
import javax.ejb.Stateless;
import javax.inject.Inject;
@Stateless
public class Messaging {
    @Inject
    MessageStore messageStore;
    @Asynchronous
    public void store(Message message){
        messageStore.store(message);
    }
}

The MessageStore class in Listing 6 is a Data Access Object (DAO) that encapsulates access to the EntityManager.
Code Listing 6: A CDI bean from the control layer 
package com.tm.messageme.business.messaging.control;
import com.tm.messageme.business.messaging.entity.Message;
import javax.persistence.EntityManager;
import javax.persistence.PersistenceContext;
public class MessageStore {
    @PersistenceContext
    EntityManager em;
    public void store(Message message){
        em.persist(message);
    }
}

ECB: A Pragmatic Separation of Concerns
If you review the packaging of the application described above, you will notice separate boundary, control, and entity packages. This packaging approach is an implementation of the Entity Control Boundary (ECB) pattern. The boundary layer is the facade, the control layer is responsible for the implementation of process- and entity-independent logic, and the entity layer contains rich domain objects. 
With Java EE 6 and especially the availability of JPA 2, CDI, and EJB, the implementation of all three layers can lead to empty delegate code. For example, many CRUD-based use cases can be implemented very efficiently with a single boundary acting as a facade for accessing multiple entities.
However, a direct one-to-one relationship between the concepts in the ECB pattern and packages inside a component can still be beneficial. When packages are kept separate, static analysis tools can be used more easily to measure dependencies between packages. Furthermore, frameworks such as OSGi and Jigsaw rely on the existence of separate packages to expose public APIs.
In Java EE 6, the boundary is always realized with EJBs. The control layer can contain either CDIs or EJBs, and the entity layer can contain either JPA 2 entities or transient, unmanaged entities. The final decision of whether to use a CDI or an EJB in the control layer does not have to be made up front. You can start with a CDI and convert it into an EJB down the road by using the @Stateless annotation. You may need to use an EJB in some cases, such as when you need to start a subsequent transaction with @RequiresNew, when you need to execute a method asynchronously, or when you need to roll back the current transaction by invoking SessionContext.setRollbackOnly().
CDI, on the other hand, is more suitable for integrating legacy code or implementing Strategy, Factory, or Observer software design patterns. All of these capabilities are already built in and result in far less code than with the Java SE counterpart.
When you are developing applications with the ECB pattern, the ECB layering should evolve iteratively and not be forced in a top-down way. You should start with the persistence (Entity) layer, perform unit testing, and then implement the boundary layer. For building the unit test, the EntityManager and the associated transactions need to be created and managed manually (as shown in Listing 7).
Code Listing 7: Standalone JPA unit tests 
package com.tm.messageme.business.messaging.entity;
import javax.persistence.*;
import org.junit.Test;

    @Test
    public void mappingSmokeTest() {
        EntityManagerFactory emf = Persistence.createEntityManagerFactory("test");       EntityManager em = emf.createEntityManager();
        EntityTransaction tx = em.getTransaction();
        tx.begin();
        em.persist(new Message("duke"));
        tx.commit();
    }

The persistence.xml file must also be adjusted to handle standalone execution. Specifically, the transaction type should be changed to RESOURCE_LOCAL and a JDBC connection (instead of a datasource) must be configured explicitly, as shown in Listing 8.
Code Listing 8: persistence.xml for standalone JPA unit tests 
<persistence>
  <persistence-unit name="test" transaction-type="RESOURCE_LOCAL">
    <provider>org.eclipse.persistence.jpa.PersistenceProvider</provider>
    <class>com.abien.messageme.business.messaging.entity.Message</class>
    <exclude-unlisted-classes>true</exclude-unlisted-classes>
    <properties>
      <property name="javax.persistence.jdbc.url" value="jdbc:derby:
./sample;create=true"/>
      <property name="javax.persistence.jdbc.password" value="app"/>
      <property name="javax.persistence.jdbc.driver" value="org.apache.derby
.jdbc.EmbeddedDriver"/>
      <property name="javax.persistence.jdbc.user" value="app"/>
      <property name="eclipselink.ddl-generation" value="drop-and-create-tables"/>
    </properties>
  </persistence-unit>
</Persistence>

When building the control layer, note that its content will be the product of entity and boundary layer refactoring. The reusable and noncohesive parts of the boundary layer, such as queries, algorithms, or validations, along with cross-cutting concerns from the entity layer, will be extracted into CDI managed beans in the control layer. 

Using the CEC Pattern

The main purpose of the boundary in the ECB pattern is to provide a clear separation between business and presentation logic. By definition, the boundary needs to be independent of presentation logic. Even with the many compromises you may make in your architecture, a clear separation between the business and UI technology is a must. In practice, UI logic tends to vary more frequently than business logic. It is common to produce business logic that can be accessed by a Web client (such as JSF 2), a rich client (such as Swing or Eclipse RCP), and REST at the same time. 
In the case of JSF 2, CDI is again the easiest choice for implementing a controller or a presenter. CDI managed beans can be directly bound to the JSF 2 view via EL, and the boundary (EJB 3.1) can be directly injected into the presenter. The presenter (or a controller) can be directly captured with an @Stereotype annotation. It works like a macro—you can place in it CDI annotations that get expanded with the annotation. A stereotype is a regular Java annotation represented by @Stereotype: 
@Named
@RequestScoped
@Stereotype
@Retention(RUNTIME)
@Target(TYPE)
public @interface Presenter {}

This custom stereotype can be applied instead of @Named and @RequestScoped—just like a macro. All CDI annotations identifying the presenter pattern can then be replaced with 
@Presenter
public class Index {//}

The purpose of the presenter is to implement presentation logic. The structure of the presenter is tightly coupled with the view, in that the state of a JSF component in the view is mapped to a property inside the presenter. The property can be either a value (with value binding) or the component instance itself (with component binding). In trivial cases, there is a one-to-one relationship between the view and the presenter. The presenter contains the view’s data as well as all the presentation logic. Injecting the boundary into the presenter involves using the @Inject annotation.
As the amount of presentation logic grows inside the presenter, the code can become harder to maintain and test. With CDI, it is fairly easy to split the monolithic presenter into separate data and presentation logic parts. For example, the following code shows how to refactor the backing bean from the earlier example by moving the save method into a newly created IndexPresenter bean. The presenter annotation is duplicated and renamed @View, and the bean is renamed IndexView: 
@View
public class IndexView {
    private Message message = new Message();
    public Message getMessage() {
        return message;
    }
}

The IndexPresenter bean gets the old @Presenter annotation. As the following code shows, the only purpose of the IndexPresenter bean in this case is to implement the presentation logic. 
@Presenter
public class IndexPresenter {
    @Inject
    Messaging boundary;
    @Inject
    IndexView indexView;
public void save(){
        boundary.store(indexView.getMessage());
    }
}

Because the boundary and the view are injected into the IndexPresenter, they can be easily mocked out. In a unit test environment, both fields would be set directly with the mock, whereas in a production environment, the container would perform the injection and set the actual dependency. Because the unit test and the IndexPresenter reside in the same package, the default visible fields can be set directly. Private fields with public setters can be used, but packagewide fields are good enough in most cases and can reduce code size.
Listing 9 shows how to test the presentation logic by mocking out the IndexView as well as the boundary Messaging class. The test, which invokes the IndexPresenter.save() method, is successful if the method store gets invoked exactly once with the Message-Instance being returned by the IndexView. Verifying the invocation means passing the mock to the Mockito.verify() method. The IndexView is mocked out to manipulate the return value without interacting with the JSF rendering.
Code Listing 9: IndexPresenterTest—with mocked-out view and boundary 
package com.tm.messageme.presentation;
//...other imports
import org.junit.Before;
import org.junit.Test;
import static org.mockito.Mockito.*;

public class IndexPresenterTest {
    private IndexPresenter cut;
    @Before
    public void initialize(){
        this.cut = new IndexPresenter();
    }
    @Test
    public void save() {
        this.cut.boundary = mock(Messaging.class);
        this.cut.indexView = mock(IndexView.class);
        Message expected = new Message("duke");
        when(this.cut.indexView.getMessage()).thenReturn(expected);
        cut.save();
        verify(this.cut.boundary,times(1)).store(expected);
    }
}

The Messaging boundary is mocked out for a different reason: to verify that the expected method actually gets invoked: 
public void save(){
    boundary.store(indexView.getMessage());
    }

The design of the JSF 2 presentation is similar to that of a rich Swing application. Common patterns such as Model-View-Controller and their refinements—Supervising Controller and Passive View—can be applied to JSF 2 as well. The main difference between JSF and a rich client technology is the way the view is rendered. In Swing the developer implements the view in Java, whereas in JSF 2 the developer uses XHTML markup. In JSF 2 the values of the component can be directly bound to a corresponding class, whereas in Swing they are usually stored in the view itself or in the model.
For the implementation of data-driven use cases such as CRUD, the Supervising Controller is a better choice than the Passive View. In the Supervising Controller pattern, a single backing bean (IndexView) is responsible for managing both the presentation logic and the state of the view. In more-sophisticated use cases, the Passive View variant may be more applicable. In the Passive View pattern, the backing bean is split into the view and presentation logic, and the presentation logic is extracted from the IndexView to the IndexPresenter.
CDI is best suited for the implementation of the presentation layer. Because of the built-in cross-cutting concerns (such as transactions, concurrency, asynchronous execution, monitoring, and throttling), the boundary of the business logic is realized as an EJB. The business component can be realized either as EJBs or CDIs. In general, you can start with CDIs and, over time, replace managed beans in special cases with EJBs. The CDI-EJB-CDI (CEC) pattern is the simplest and most pragmatic choice for Java EE 6. 

Making Interfaces Useful

EJB 3.0 (in Java EE 5) required separate interfaces for bean classes. To avoid naming collisions, developers often had to resort to well-defined naming conventions such as XyzLocal/XyzRemote and XyzBean. In Java EE 6, interfaces for EJBs and CDIs are now optional. Public EJB or CDI methods can now expose a “no interface” view, with no loss of functionality. 
This new functionality makes interfaces meaningful again. As opposed to the obligatory, nondescript use of interfaces with earlier releases, interfaces in Java EE 6 can be used for the implementation of the Strategy pattern; implementation of a public API; or strict separation of modules, which makes the code more expressive. An interface can also signal the “protected variations” of a system, and direct dependencies between classes can be used for code that is less likely to vary.
You can safely start without any interfaces and introduce them later as the need arises. This approach is fundamentally different from that in Java EE 5. Compared to Java 2 Platform, Enterprise Edition (J2EE) from 2003, Java EE 6 code is simpler, in terms of the elimination of several layers, indirections, and abstractions. Unlike J2EE, Java EE 6 consists of annotated classes without any dependencies on the platform. This approach eliminates the need to separate business logic from the infrastructure and makes the majority of J2EE patterns and best practices superfluous. In Java EE 6, simple cases can be solved with two layers: presentation and business logic. The EntityManager is already a good enough abstraction of the underlying persistence, so there is no need for additional indirections.
Maintainable Java EE 6 applications are written according to the YAGNI (You Ain’t Gonna Need It), DRY (Don’t Repeat Yourself), and KISS (Keep It Simple, Stupid) principles. Design patterns and best practices are introduced in a bottom-up—not a top-down—fashion. The patterns are always motivated by functional and nonfunctional requirements, not by the shortcomings of the platform. This approach represents the biggest difference between Java EE 6 and previous J2EE releases. In J2EE many of the design decisions were made up front, driven by the J2EE platform dependencies.
By contrast, the Java EE 6 development process focuses on function:
  1. Write simple code that directly solves the business problem.
  2. Verify the business logic with unit tests.
  3. Cut redundancies and improve the design with refactoring.
  4. Stress-test your application.
  5. Go back to 1.
Design and architecture are driven by concrete requirements rather than generic and architectural best practices. By continually stress-testing your application (at least once per week), you can more easily justify a simple design with hard facts to gain insight into system behavior under stress.