The Business Layer (Java EE 7 First Look)

Exclusive offer: get 50% off this eBook here
Java EE 7 First Look

Java EE 7 First Look — Save 50%

Discover the new features of Java EE 7 and learn to put them together to build a large-scale application with this book and ebook.

$23.99    $12.00
by NDJOBO Armel Fabrice | November 2013 | Enterprise Articles

In this article by NDJOBO Armel Fabrice, author of Java EE 7 First Look, we will begin with a presentation of improvements in the business layer and then, in a small project, we will try to put together some of the specifications seen previously. The topics to be covered include:

  • Enterprise JavaBeans 3.2

  • Putting all Java EE 7 specifications together

(For more resources related to this topic, see here.)

Enterprise JavaBeans 3.2

The Enterprise JavaBeans 3.2 Specification was developed under JSR 345. This section just gives you an overview of improvements in the API. The complete document specification (for more information) can be downloaded from http://jcp.org/aboutJava/communityprocess/final/jsr345/index.html.

The businesslayer of an application is the part of the application that islocated between the presentationlayer and data accesslayer. The following diagram presents a simplified Java EE architecture. As you can see, the businesslayer acts as a bridge between the data access and the presentationlayer.

It implements businesslogic of the application. To do so, it can use some specifications such as Bean Validation for data validation, CDifor context and dependency injection, interceptors to intercept processing, and so on. As thislayer can belocated anywhere in the network and is expected to serve more than one user, it needs a minimum of non functional services such as security, transaction, concurrency, and remote access management. With EJBs, the Java EE platform provides to developers the possibility to implement thislayer without worrying about different non functional services that are necessarily required.

In general, this specification does not initiate any new major feature. It continues the work started by thelast version, making optional the implementation of certain features that became obsolete and adds slight modification to others.

Pruning some features

After the pruning process introduced by Java EE 6 from the perspective of removing obsolete features, support for some features has been made optional in Java EE 7 platform, and their description was moved to another document called EJB 3.2 Optional Features for Evaluation. The features involved in this movement are:

  • EJB 2.1 and earlier Entity Bean Component Contract for Container-Managed Persistence

  • EJB 2.1 and earlier Entity Bean Component Contract for Bean-Managed Persistence

  • Client View of EJB 2.1 and earlier Entity Bean

  • EJB QL: Querylanguage for Container-Managed Persistence Query Methods

  • JAX-RPC-based Web Service Endpoints

  • JAX-RPC Web Service Client View

The latest improvements in EJB 3.2

For those who have had to use EJB 3.0 and EJB 3.1, you will notice that EJB 3.2 has brought, in fact, only minor changes to the specification. However, some improvements cannot be overlooked since they improve the testability of applications, simplify the development of session beans or Message-Driven Beans, and improve control over the management of the transaction and passivation of stateful beans.

Session bean enhancement

A session bean is a type of EJB that allows us to implement businesslogic accessible tolocal, remote, or Web Service Client View. There are three types of session beans: stateless for processing without states, stateful for processes that require the preservation of states between different calls of methods, and singleton for sharing a single instance of an object between different clients.

The following code shows an example of a stateless session bean to save an entity in the database:

@Stateless public class ExampleOfSessionBean { @PersistenceContext EntityManager em; public void persistEntity(Object entity){ em.persist(entity); }}

Talking about improvements of session beans, we first note two changes in stateful session beans: the ability to executelife-cycle callback interceptor methods in a user-defined transaction context and the ability to manually disable passivation of stateful session beans.

It is possible to define a process that must be executed according to thelifecycle of an EJB bean (post-construct, pre-destroy). Due to the @TransactionAttribute annotation, you can perform processes related to the database during these phases and control how they impact your system. The following code retrieves an entity after being initialized and ensures that all changes made to the persistence context are sent to the database at the time of destruction of the bean. As you can see in the following code, TransactionAttributeType of init() method is NOT_SUPPORTED; this means that the retrieved entity will not be included in the persistence context and any changes made to it will not be saved in the database:

@Stateful public class StatefulBeanNewFeatures { @PersistenceContext(type= PersistenceContextType.EXTENDED) EntityManager em; @TransactionAttribute(TransactionAttributeType.NOT_SUPPORTED) @PostConstruct public void init(){ entity = em.find(...); } @TransactionAttribute(TransactionAttributeType.REQUIRES_NEW) @PreDestroy public void destroy(){ em.flush(); } }

The following code demonstrates how to control passivation of the stateful bean.

Usually, the session beans are removed from memory to be stored on the disk after a certain time of inactivity. This process requires data to be serialized, but during serialization all transient variables are skipped and restored to the default value of their data type, which is null for object, zero for int, and so on. To prevent theloss of this type of data, you can simply disable the passivation of stateful session beans by passing the false value to the passivationCapable attribute of the @Stateful annotation.

@Stateful(passivationCapable = false) public class StatefulBeanNewFeatures { //... }

For the sake of simplicity, EJB 3.2 has relaxed the rules to define the defaultlocal or remote business interface of a session bean. The following code shows how a simple interface can be considered aslocal or remote depending on the case:

//In this example, yellow and green are local interfaces public interface yellow { ... } public interface green { ... } @Stateless public class Color implements yellow, green { ... } //In this example, yellow and green are local interfaces public interface yellow { ... } public interface green { ... } @Local @Stateless public class Color implements yellow, green { ... } //In this example, yellow and green are remote interfaces public interface yellow { ... } public interface green { ... } @Remote @Stateless public class Color implements yellow, green { ... } //In this example, only the yellow interface is exposed as a remote interface @Remote public interface yellow { ... } public interface green { ... } @Stateless public class Color implements yellow, green { ... } //In this example, only the yellow interface is exposed as a remote interface public interface yellow { ... } public interface green { ... } @Remote(yellow.class) @Stateless public class Color implements yellow, green { ... }

EJBlite improvements

Before EJB 3.1, the implementation of a Java EE application required the use of a full Java EE server with more than twenty specifications. This could be heavy enough for applications that only need some specification (as if you were asked to take a hammer to kill a fl y). To adapt Java EE to this situation, JCP (Java Community Process) introduced the concept of profile and EJBlite. Specifically, EJBlite is a subset of EJBs, grouping essential capabilities forlocal transactional and secured processing. With this concept, it has become possible to make unit tests of an EJB application without using the Java EE server and it is also possible to use EJBs in web applications or Java SE effectively.

In addition to the features already present in EJB 3.1, the EJB 3.2 Specification has added support forlocal asynchronous session bean invocations and non persistent EJB Timer Service. This enriches the embeddable EJBContainer, web profiles, and augments the number of testable features in an embeddable EJBContainer. The following code shows an EJB packaged in a WAR archive that contains two methods. The asynchronousMethod() is an asynchronous method that allows you to compare the time gap between the end of a method call on the client side and the end of execution of the method on the server side. The nonPersistentEJBTimerService() method demonstrates how to define a non persistent EJB Timer Service that will be executed every minute while the hour is one o'clock:

@Stateless public class EjbLiteSessionBean { @Asynchronous public void asynchronousMethod(){ try{ System.out.println("EjbLiteSessionBean - start : "+new Date()); Thread.sleep(1000*10); System.out.println("EjbLiteSessionBean - end : "+new Date()); }catch(Exception ex){ ex.printStackTrace(); } } @Schedule(persistent = false, minute = "*", hour = "1") public void nonPersistentEJBTimerService(){ System.out.println("nonPersistentEJBTimerService method executed"); } }

Changes made to the TimerService API

The EJB 3.2 Specification enhanced the TimerService APiwith a new method called getAllTimers(). This method gives you the ability to access all active timers in an EJB module. The following code demonstrates how to create different types of timers, access their information, and cancel them; it makes use of the getAllTimers() method:

@Stateless public class ChangesInTimerAPI implements ChangesInTimerAPILocal { @Resource TimerService timerService; public void createTimer(){ //create a programmatic timer long initialDuration = 1000*5; long intervalDuration = 1000*60; String timerInfo = "PROGRAMMATIC TIMER"; timerService.createTimer(initialDuration, intervalDuration, timerInfo); } @Timeout public void timerMethodForProgrammaticTimer(){ System.out.println("ChangesInTimerAPI - programmatic timer : "+new Date()); } @Schedule(info = "AUTOMATIC TIMER", hour = "*", minute = "*") public void automaticTimer(){ System.out.println("ChangesInTimerAPI - automatic timer : "+new Date()); } public void getListOfAllTimers(){ Collection alltimers = timerService.getAllTimers(); for(Timer timer : alltimers){ System.out.println("The next time out : "+timer. getNextTimeout()+", " + " timer info : "+timer.getInfo()); timer.cancel(); } } }

In addition to this method, the specification has removed the restrictions that required the use of javax.ejb.Timer and javax.ejb.TimerHandlereferences only inside a bean.

Java EE 7 First Look Discover the new features of Java EE 7 and learn to put them together to build a large-scale application with this book and ebook.
Published: November 2013
eBook Price: $23.99
Book Price: $39.99
See more
Select your format and quantity:

Harmonizing with JMS's novelties

A Message-Driven Bean (MDB) is a kind of a JMS Messagelistener allowing Java EE applications to process messages asynchronously. To define such a bean, simply decorate a simple POJO class with @MessageDriven annotation and make it implement the javax.jms.MessageListener interface. This interface makes available to the MDB the onMessage method that will be called each time a new message is posted in the queue associated with the bean. That's why you have to put inside this method the businesslogic for the processing of incoming messages. The following code gives an example of an MDB that notifies you when a new message arrives by writing in the console:

@MessageDriven(activationConfig = {
@ActivationConfigProperty(propertyName = "destinationType",
propertyValue = "javax.jms.Queue"),
@ActivationConfigProperty(propertyName = "destinationLookup",
propertyValue = "jms/messageQueue")
})
public class MessageBeanExample implements MessageListener {
public MessageBeanExample() {
}
@Override
public void onMessage(Message message) {
try{
System.out.println("You have received a new message of type
: "+message.getJMSType());
}catch(Exception ex){
ex.printStackTrace();
}
}
}

Given the changes in JMS 2.0 Specification, the EJB 3.2 Specification has a revisedlist of JMS MDB activation properties to conform to thelist of standard properties.

These properties are: destinationLookup, connectionFactoryLookup, clientId, subscriptionName, and shareSubscriptions. In addition, it has added the ability in MDB to implement a no-method messagelistener, resulting in the exposure of all public methods of the bean as messagelistener methods.

Other improvements

As we said earlier, the EJB 3.1 Specification has given developers the opportunity to test EJB applications outside a full Java EE server. This was made possible through an embeddable EJBContainer. The following example demonstrates how to test an EJB using an embeddable EJBContainer:

@Test
public void testAddition(){
Map<String, Object> properties = new HashMap<String, Object>();
properties.put(EJBContainer.APP_NAME,
"chapter05EmbeddableEJBContainer");
properties.put(EJBContainer.MODULES, new File("target\\classes"));
EJBContainer container = javax.ejb.embeddable.EJBContainer.
createEJBContainer(properties);
try {
NewSessionBean bean = (NewSessionBean) container.getContext().
lookup("java:global/chapter05EmbeddableEJBContainer/NewSessionBean");
int restult = bean.addition(10, 10);
Assert.assertEquals(20, restult);
} catch (NamingException ex) {
Logger.getLogger(AppTest.class.getName()).log(Level.FINEST,
null, ex);
} finally {
container.close();
}
}

Since the embeddable EJBContainer reference by maven was not up-to-date while writing this book (which caused the error "No EJBContainer provider available"), idirectly addressed the glassfish-embedded-static-shell.jar file in the following way:

  • Maven variable declaration:

    <properties> <glassfish.installed.embedded.container>glassfish_dir\lib\ embedded\glassfish-embedded-static-shell.jar</glassfish.installed. embedded.container> </properties>

  • Declaration of dependence:

    <dependency> <groupId>glassfish-embedded-static-shell</groupId> <artifactId>glassfish-embedded-static-shell</artifactId> <version>3.2</version> <scope>system</scope> <systemPath>${glassfish.installed.embedded.container}</ systemPath> </dependency>

During operation, the embeddable EJBContainer acquires resources that would normally be released at the end of the process to allow other applications to take advantage of the maximum power of the machine. In the previous version of the specification, a developer used the EJBContainer.close() method in a finally block to perform this task. But, with the try-with-resources statement introduced in Java SE 7, EJB 3.2 added the implementation of the java.lang.AutoCloseable interface in the EJBContainer class to free the developer from a task that could easily be forgotten and have negative repercussions on the performance of a machine. Now, the embeddable EJBContainer will be automatically closed at the end of a statement, provided that it is declared as a resource in a try-with-resources statement. Thus, we nolonger need a finally blocklike in the earlier example, which simplifies the code. The following example demonstrates how to take advantage of the try-with-resources statement while testing EJB with an embeddable EJBContainer:

@Test
public void testAddition(){
//...
try(EJBContainer container = javax.ejb.embeddable.EJBContainer.cre
ateEJBContainer(properties);) {
//...
} catch (NamingException ex) {
Logger.getLogger(AppTest.class.getName()).log(Level.FINEST,
null, ex);
}
}

The final improvement of this specification concerns removal of the restriction on obtaining the current classloader when you want to access files or directories in the file system from a bean.

Putting it all together

The example that will allow us to put together most of the APIs already studied is an online preregistration site. In this example, we will not write any code. We limit ourselves to the presentation of an analysis of a problem that will help you understand how to use each of the pieces of code that are used to illustrate points in this book, in order to make a quality application based on the latest functionality of Java EE 7.

Presenting the project

The virtual enterprise software technology has received from a private university the order for creating an application to manage the preregistration of students online (candidate registration, validation of applications, and notifications of different candidates) and provide a real-time chat room for connected students. Furthermore, for statistical purposes, the system will allow the ministry of education access to certain information from a heterogeneous application.

The system called ONPRINS must be robust, efficient, and available 24 x 7 during periods of registration.

The business domain model in the following diagram represents the main objects of our system (the required application will be built based on these objects):

Disclaimer

These diagrams have been designed and built in Enterprise Architect, by Sparx Systems.

Use Case Diagram (UCD)

The following diagram represents all the features that will be supported by our system. We have three actors as follows:

  • A Candidate is any user wishing to preregister for a department. To this end, it has the ability to view thelist of departments, select a department, and complete and submit the application form. Through a chat room, he/she can share his/her ideas with all candidates connected with respect to a given theme.

  • An Administrator is a special user who has the right to run the validation process of preregistration. It is this process that creates the students and sends e-mails to different candidates tolet them know whether they have been selected or not.

  • The Ministry of Education is a secondary actor of the system; it seeks access to the number of preregistered students and thelist of students during an academic year.

Class diagram

The following class diagram shows all the main classes used for the realization of our online preregistration. This diagram also highlights the relationships that exist between different classes.

The CandidateSessionBean class is a bean that records the preregistration of candidates through registerCandidate method. It also provides methods for accessing all the registered candidates (listOfCandidates) and preregistered students (listOfStudents).

The InscriptionValidationBean class contains the startValidationBatchJob method which, as its name suggests,launches batch processing to validate the preregistration and notify different candidates. Batch processing presented here is the chunk type in which the ValidationReader class is used to read the data useful for validation, the ValidationProcessor class is used to validate the preregistration, and the ValidationWriter class is used to notify the candidate.

This class also serves to create a student when the candidate is selected. As you can see, in order to send an e-mail, the ValidationWriter class firstly sends a JMS message through MsgSenderSessionBean to the component responsible for sending the e-mail. This allows us to avoid blockages in ValidationWriter when there is a connection breakdown. Also, in the batch process, we have thelistener ValidationJobListener, which enables us to record a certain amount of information in the validation table at the end of batch processing.

For the sake of simplicity and reusability, navigation between web pages during the preregistration of a candidate (departmentList.xhtml, acceptanceConditions. xhtml, identificationInformation.xhtml, contactInformation. xhtml, medicalInformation.xhtml, schoolInformation.xhtml, and InformationValidation.xhtml) will be made using the Faces Flow. On the other hand, the content of various pages will be structured with the Resourcelibrary Contracts and communication in the chat room will be managed using WebSocket; it is for this reason that you have the ChatServerEndPoint class, which is the server endpoint for this communication.

The execution of the validation process of preregistration is made from the inscriptionValidation.xhtml facelet. In order to give the administrator a feedback on the progress of the validation process, the facelet will contain a progress bar updated in real time, whichleads us once again to use the WebSocket protocol.

Component diagram

The following diagram shows the various components that constitute our system.

As you can see, the exchange of data between the application of the ministry and ONPRINS will be through web services, which aims to make both systems completely independent from one another, while our system uses a connector to have access to user information stored on the ERP system of the university.

Summary

As promised, in this article we presented the innovations introduced by EJBs, and then focused on the analysis and design of an application for online preregistration. In this exercise, we were able to look at practical cases allowing us to use almost all of the concepts already discussed (WebSocket and Faces Flow) and discover new concepts (web service, connector, and Java e-mail).

Resources for Article:


Further resources on this subject:


Java EE 7 First Look Discover the new features of Java EE 7 and learn to put them together to build a large-scale application with this book and ebook.
Published: November 2013
eBook Price: $23.99
Book Price: $39.99
See more
Select your format and quantity:

About the Author :


NDJOBO Armel Fabrice

NDJOBO Armel Fabrice is a Design Computer Engineer and graduate from the National Advanced school of Engineering Cameroon, and Oracle Certified Expert, Java EE 6 Java Persistence API Developer. In the past, he has worked with Java EE to develop several systems among which are a helpline system and a commercial management application. He currently works on several systems based on EJB, Spring and ICEFaces solutions. In addition, he has made a technical review of the books Pro Spring Integration published by Apress and Beginning EJB 3, Java EE published by Apress. He is also a copywriter in developpez.com (his home page is: http://armel-ndjobo.developpez.com/).

Books From Packt


 

JasperReports for Java Developers
JasperReports for Java Developers

JavaFX 1.2 Application Development Cookbook
JavaFX 1.2 Application Development Cookbook

Java EE 7 Developer Handbook
Java EE 7 Developer Handbook

Java EE 6 Cookbook for Securing, Tuning, and Extending Enterprise Applications
Java EE 6 Cookbook for Securing, Tuning, and Extending Enterprise Applications

Java EE Development with Eclipse
Java EE Development with Eclipse

Java EE 6 with GlassFish 3 Application Server
Java EE 6 with GlassFish 3 Application Server

Java EE 5 Development with NetBeans 6
Java EE 5 Development with NetBeans 6

Java EE 5 Development using GlassFish Application Server
Java EE 5 Development using GlassFish Application Server


No votes yet

Post new comment

CAPTCHA
This question is for testing whether you are a human visitor and to prevent automated spam submissions.
3
C
T
q
E
e
Enter the code without spaces and pay attention to upper/lower case.
Code Download and Errata
Packt Anytime, Anywhere
Register Books
Print Upgrades
eBook Downloads
Video Support
Contact Us
Awards Voting Nominations Previous Winners
Judges Open Source CMS Hall Of Fame CMS Most Promising Open Source Project Open Source E-Commerce Applications Open Source JavaScript Library Open Source Graphics Software
Resources
Open Source CMS Hall Of Fame CMS Most Promising Open Source Project Open Source E-Commerce Applications Open Source JavaScript Library Open Source Graphics Software