Book Image

Java EE 7 Developer Handbook

By : Peter A. Pilgrim
Book Image

Java EE 7 Developer Handbook

By: Peter A. Pilgrim

Overview of this book

<p>The seventh edition of the Enterprise Java platform is aimed at helping Java engineers take advantage of the advancements in HTML5 and web standards. Web Sockets, asynchronous input and output with Servlets, and strong type safety through the CDI containers will ensure that Java EE 7 remains popular for server-side applications.<br />If you are a user aiming to get acquainted with the Java EE 7 platform, this book is for you.</p> <p>"Java EE 7 Developer Handbook" provides a solid foundation of knowledge for developers to build business applications. Following the lead of Agile practices, there is a focus on writing tests to demonstrate test-driven development principles, using the embedded GlassFish 4.0 container examples and the Gradle build system. You will learn about CDI, EJB, JPA, JMS, MDB, Servlets, WebSocket, JAX-RS, Bean Validation, and so much more.</p> <p>"Java EE 7 Developer Handbook" is designed as a companion to the professional software developer who quickly needs to lookup some working code, understand the basics of the framework, and then go out and fulfill the business contract with the customer. Typically, engineers are under pressure to develop professional code that is of high quality and contains a low number of bugs. Java EE 7 Developer Handbook relies heavily on the Arquillian framework to illustrate how much easier it is to write Java EE tests, and together with the modern practice of writing containerless applications that actually embed an application container, developing agile Java EE suddenly becomes reasonable, smart, pragmatic, and achievable.</p> <p>You will start off with an overview of the Java EE platform: the containers, the design, and architecture. From there, you can follow the path of the CDI, the true gem of the framework, and then the server side end point, EJB. It is completely up to you when and if you want to learn about Java persistence. However, don’t miss out on the highlights of Java EE 7 such as WebSocket, Bean Validation, and asynchronous Servlet API.</p> <p>"Java EE 7 Developer Handbook" is a vertical slice through standard Java enterprise architecture. If you have been wondering why developers have invested so much time and effort into learning topics such as Enterprise Java Beans, you will quickly understand why when you find out the difference between stateful and stateless Beans. Best of all, this book covers the topic from the perspective of new API and new modern practices. For instance, you, the developer and designer, are expected to write applications with annotations in comparison with J2EE. Java EE 7 Developer Handbook incorporates helpful hints and tips to get the developer up to speed in a short amount of time on EJB, CDI, Persistence, Servlet, JMS, WebSocket, JAX-RS and Bean Validation, and much more.</p> <p>"Java EE 7 Developer Handbook" is the reference guide you need beside you at your desk.</p>
Table of Contents (23 chapters)
Java EE 7 Developer Handbook
Credits
About the Author
Acknowledgment
About the Reviewers
www.PacktPub.com
Preface
Index

Preface

Jack Dempsey said, "A champion is somebody who gets up, when he can't".

This is a book about the Java EE 7 platform and the goal is to guide the software developers, designers, and interested architects. The book is aimed at the technical delivery and will be of service to those who are curious about Java EE. The intention of this book is to be a reference guide to programmers who are already building enterprise applications at a novice level and feel that this is the time to improve their knowledge. The book is also relevant to experienced Java developers, who need to stay up-to-date with the seventh edition of the Java EE platform.

My aim is to take you on this stupendous journey so that eventually you will have mastery, satisfaction, and a grand element of purpose around the Java EE 7 platform. After reading this book, you will be able to start building the next generation Java application for your enterprise with all the flair and confidence of a programmer with experienced technical know-how. Mastery is the inner urge to get better at doing stuff that you have a passion for and this book will show you how much you can achieve. Your passion for Java EE 7 will drive your satisfaction.

Your journey will start with an introduction to the Java EE 7 platform, which provides an overview of the initiative, mission, and the description of the umbrella specification and the individual specifications. There you will find, brief explanations of the highlights of the new APIs and several updated ones. In the first chapter, we will see a sample application from the beginning. From then onwards, the book delves straight into the Context and Dependency Injection, which is one of the most important APIs in Java. After that, the book moves onto Enterprise Java Beans and discussion of the server-side endpoints. Along the way, the book introduces Gradle as a build tool and Arquillian, which is an integration-testing framework. Your journey continues with Java Persistence and follows on with chapters dedicated to JMS, Java Servlets, RESTful services, and WebSocket.

This is a reference book. The contents around Java EE 7 are not by any means exhaustive. This book only serves as a start and now, it is up to you to venture forth. Good luck!

What this book covers

Chapter 1, Java EE 7 HTML5 Productivity, introduces the developer to the new features of the Java EE 7 platform. The reader is presented with a cursory view of WebSocket and JAX-RS 2.0.

Chapter 2, Context and Dependency Injection, is a study in the managed beans that have contextual scope. The chapter delves into qualifiers, providers, and Interceptors.

Chapter 3, Enterprise Java Beans, is an overview of the oldest endpoint in Enterprise Java. After reading this chapter, the reader will be comfortable with the session beans, asynchronous methods, and poolable instances.

Chapter 4, Essential Java Persistence API 3.2, is the first of a double that dives into JPA from the top to the bottom. Developers will understand entities, tables, and the primary key fields and properties.

Chapter 5, Object-Relational Mapping with JPA, follows on from the previous chapter and engages the reader into mapping objects with JPA. We cover all of the cardinal relationships including one-to-one and one-to-many.

Chapter 6, Java Servlets and Asynchronous Request-Response, takes a break from the persistence modeling to focus on Java Servlets and writing Servlet filters and context listener. The reader will learn about the asynchronous input and output with Java Servlets.

Chapter 7, Java API for HTML5WebSocket, tackles the WebSocket technology from the perspective of Java. The developer will learn how to build new applications using this important API from both server and client.

Chapter 8, RESTful Services JAX-RS 2.0, is a deep dive into the Java RESTful service standard in its second edition. The reader will learn about the client-side JAX-RS API as well as new server-side features.

Chapter 9, Java Message Service 2.0, is a tour around the latest JMS API on the Java EE 7 platform. JMS is all about asynchronous message processing.

Chapter 10, Bean Validation, is a thorough engineering introduction into the wonderful world of constraint validation around POJOs. You will learn how to write your own custom constraint checks, and to group and order sets of validation constraints.

Chapter 11, Advanced Topics in Persistence, is a final dedicated chapter to persistence and it covers recent corner cases that have been recently fixed. The reader will learn how to invoke stored procedures and create fetch plans among other techniques.

Appendix A, Java EE 7 Platform, is a reference around the platform container configuration. This appendix has a material about XML configuration, the JNDI name space and packaging. It also has handy section on installing GlassFish 4.0, manually.

Appendix B, Java EE 7 Persistence, covers the configuration of JPA and most importantly the persistence unit. It has a useful table of all the JPA 2.1 properties. This appendix delves into miscellaneous parts of the specification including stateless session EJB, transactions, and concurrency.

Appendix C, Java EE 7 Transactions, is dedicated completely to Java EE transactions. The reader will find a useful overview of ACID principles, and local and distributed transaction. There is an excellent coverage of the heuristic failures and illustrations of the main transaction and consistency issues.

Appendix D, Java EE 7 Assorted Topics, is divided into two sections, namely: Concurrency Utilities API and JSON-Processing API. These are two new brand editions to the Java EE 7 specification. The reader will find these sections to be very handy references.

Online Chapter, Moving Java EE.next to the Cloud, is an explorative chapter from the heart that discusses the potential repercussions for the Java EE platform migrating to the cloud-computing environment.

You can download the online chapter from http://www.packtpub.com/sites/default/files/downloads/7942EN_Chapter_12_Moving_Java_EE_next_to_the_cloud.pdf.

What you need for this book

You will only need the Java SDK, an IDE, or a text editor, and the patience to learn. Technically, you can work with IntelliJ, Eclipse, or NetBeans to compile the source from the book. All of the source code examples in the book were created with the Gradle build tool, which is an open source software. They were created and executed against the Java EE 7 reference implementation: GlassFish Open Source Server Version 4.0.1.

Who this book is for

This book is for experienced Java developers. This book is not for dummies. The book is practically busting out of its seams, because there is so much information about all of the Java EE 7 technologies; therefore, we have included only the relevant stuff. Java EE 7 Developer Handbook covers the most crucial types of endpoints for new enterprise. This book will help many of you that have had prior experience with the platform. Whilst this book will not provide all the best practice and design patterns for Java EE 7, it does teach you the basics and the insider knowledge that will help you hunt for that information further afield.

Given there are more than 32 individual specifications involved in the umbrella Java EE 7, unfortunately, we could not fit every single topic inside this book. So that means coverage around Java Server Faces, Java EE Connector Architecture, and the new Batch API fell outside the remit of this volume. Something had to give, sadly, to ensure that we did include the most common denominator technologies that an engineer will face. We do give full attention to brand new Java EE 7 APIs, such as Java WebSocket, Concurrency Utilities, and JSON Processing API.

If you are unlucky (or lucky) like us, one day you arrive at your workplace, and suddenly you are told or requested to learn a new technology in a jig time. You already have a realization about time, which is a precious commodity and we should not waste it. This is why we focused on using up-to-date technology and build practices that we think are turning the world over.

Test Driven Development (TDD) has almost baked itself into the stone in the engineering world. Who professionally nowadays can proclaim within any organization that we do not test our software? This book reflects some of the best practices, by illustrating the testing codes. This book is not, however, a full treatise in testing, rather we show how Java EE 7 is more amenable than ever to write tests, if TDD is the way you want to practice your development.

Gradle is the next-generation build system of choice for us. It is rapidly being adopted and has won over some of the world's leading engineering teams in open source and behind closed doors. Gradle is adopted by Google's Android, Oracle's Open JavaFX project, and I can claim personally that a certain department in London at the Barclays Retail bank uses it daily. Gradle can work with Maven and Apache Ivy repositories.

Java EE 7 is the stopgap specification, we think, between the traditional client-server model and embracing the cloud platform. So the question is, when do we want to learn it? You will be rewarded, however, if you make the grade.

Conventions

In this book, you will find a number of styles of text that distinguish between different kinds of information. Here are some examples of these styles, and an explanation of their meaning.

Code words in text, database table names, folder names, filenames, file extensions, pathnames, dummy URLs, user input, and Twitter handles are shown as follows: "We placed ProjectWebSocketServerEndpoint and ProjectRESTServerEndpoint in the control subpackage, because these POJOs are manipulating the entities on behalf of the client side."

A block of code is set as follows:

package je7hb.intro.xentracker.entity;

import org.hibernate.validator.constraints.NotEmpty;
import javax.persistence.*;
import javax.validation.constraints.Size;
import java.util.*;

@Entity
public class Project {
  @Id @GeneratedValue(strategy = GenerationType.AUTO)
  @Column(name = "PROJECT_ID") private Integer id;
  
  @NotEmpty @Size(max = 64)
  private String name;
  
  @OneToMany(cascade = CascadeType.ALL, mappedBy = "project", fetch = FetchType.EAGER)
  private List<Task> tasks = new ArrayList<>();
  
  public Project() {/* Required for JPA */}
  public Project(String name) {this.name = name;}
  
  public Integer getId() {return id;}
  public void setId(Integer id) {this.id = id;}
  public String getName() {return name;}
  public void setName(String name) {this.name = name;}
  
  public List<Task> getTasks() {return tasks;}
  public void setTasks(List<Task> tasks) {this.tasks = tasks;}
  
  public boolean addTask(Task task) {
    if (!tasks.contains(task)) {
      Project oldProject = task.getProject();
      if (oldProject != null) {
        removeTask(task);
      }
      tasks.add(task);
      return true;
    } else {return false;}
  }
  
  public boolean removeTask(Task task) {
    if (tasks.contains(task)) {
      tasks.remove(task);
      task.setProject(null);
      return true;
    } else {return false;}
  }
  
  // hashCode(), equals(), toString() omitted
}

When we wish to draw your attention to a particular part of a code block, the relevant lines or items are set in bold:

package je7hb.basic.arquillian;
import javax.decorator.Decorator;
import javax.decorator.Delegate;
import javax.inject.Inject;

@Decorator
@Premium
public class CreditProcessorDecorator implements CreditProcessor {
  
  @Inject SanctionService sanctionService;
  @Inject @Delegate @Premium CreditProcessor processor;
  
  @Override
  public void check(String account) {
    sanctionService.sanction(account, "EURGBP");
    processor.check(account);
  }
}

Any command-line input or output is written as follows:

gradle clean
gradle eclipse
gradle idea
Gradle run
gradle build
gradle build

New terms and important words are shown in bold. Words that you see on the screen, in menus or dialog boxes for example, appear in the text like this: "Ramping up on Java concurrency".

Note

Warnings or important notes appear in a box like this.

Tip

Tips and tricks appear like this.

Reader feedback

Feedback from our readers is always welcome. Let us know what you think about this book—what you liked or may have disliked. Reader feedback is important for us to develop titles that you really get the most out of.

To send us general feedback, simply send an e-mail to , and mention the book title via the subject of your message.

If there is a topic that you have expertise in and you are interested in either writing or contributing to a book, see our author guide on www.packtpub.com/authors.

Customer support

Now that you are the proud owner of a Packt book, we have a number of things to help you to get the most from your purchase.

Downloading the example code

You can download the example code files for all Packt books you have purchased from your account at http://www.packtpub.com. If you purchased this book elsewhere, you can visit http://www.packtpub.com/support and register to have the files e-mailed directly to you. Alternatively, you can download the code from the author's GitHub account at https://github.com/peterpilgrim.

Errata

Although we have taken every care to ensure the accuracy of our content, mistakes do happen. If you find a mistake in one of our books—maybe a mistake in the text or the code—we would be grateful if you would report this to us. By doing so, you can save other readers from frustration and help us improve subsequent versions of this book. If you find any errata, please report them by visiting http://www.packtpub.com/submit-errata, selecting your book, clicking on the errata submission form link, and entering the details of your errata. Once your errata are verified, your submission will be accepted and the errata will be uploaded on our website, or added to any list of existing errata, under the Errata section of that title. Any existing errata can be viewed by selecting your title from http://www.packtpub.com/support.

Piracy

Piracy of copyright material on the Internet is an ongoing problem across all media. At Packt, we take the protection of our copyright and licenses very seriously. If you come across any illegal copies of our works, in any form, on the Internet, please provide us with the location address or website name immediately so that we can pursue a remedy.

Please contact us at with a link to the suspected pirated material.

We appreciate your help in protecting our authors, and our ability to bring you valuable content.

Questions

You can contact us at if you are having a problem with any aspect of the book, and we will do our best to address it.