Java EE 7 Overview - Wrox Press Java Programming 24-Hour Trainer 2nd (2015)

Wrox Press Java Programming 24-Hour Trainer 2nd (2015)

Lesson 25. Java EE 7 Overview

Starting from this lesson you’ll be learning about Java Enterprise Edition (Java EE, formerly J2EE), which is a powerful, mature, and widely used platform for development of distributed applications. The word enterprise doesn’t imply that it is meant only for large-scale applications. Java EE components are used for the development of everything from an application for a local pizza parlor’s website running on a five-hundred-dollar computer to a super-powerful Wall Street trading application that runs on a cluster of hundreds of interconnected servers.

This lesson is an overview of the Java EE architecture, concepts, components, and terms that will be covered in detail in the remaining lessons of this book. The goal of these lessons is to give you an understanding of how to approach the development of Java EE applications by showing you how to build small applications rather than making you read the 1,000-page manuscript that would otherwise be required for detailed coverage of this subject.

There are an abundance of online materials and books published on the subject of Java EE, and when you figure out which components are a good fit for your project, finding materials on the selected topic will not be difficult at all. My task is to help you in making that decision and getting you started in the quickest possible way. Oracle’s white paper "Introduction to Java Platform Enterprise Edition 7" is a good complement for this lesson. If you start browsing the Internet trying to find more information on Java EE, you can easily get confused by trying to compare the features of different versions of Java EE components. I highly recommend that you stay focused on the features of Java EE 7, which is the most current platform and the easiest to use. It was released in 2013.

The Big Picture

Go to your favorite online job search engine and search for job listings with the keyword Java. You’ll find thousands of job descriptions, but recruiters are looking for software developers that know more than just the Core Java that was covered in the first 24 lessons of this book. Here’s an example of one of the job ads:

Title: Java Software Developer

Skills: Java, JMS, Spring, Websphere MQ, EJB, Servlets, JDK, JUnit, Oracle, SQL

The candidate should know:

· Core Java

· Have expertise in EJB and Servlets

· Have experience with RESTFulWeb Services and JAX-RS

· JDBC (Oracle) and JPA

· JUnit

· SQL

· Eclipse IDE

· Spring Framework

· WebSphere Application Server

· JMS and WebSphere MQ

How many items from this list of skills did you recognize? You know Core Java (also known as Java SE), JDBC, Eclipse, and hopefully SQL. After studying the remaining lessons you’ll understand what most of the other skills are, why they are required, and how they all fit together. You’ll also have technical knowledge of many of the buzzwords listed there.

JCP, JSR, and Other Acronyms

The Java community is accustomed to using lots of acronyms. Initially these acronyms might sound intimidating and confusing, but with a little effort they will make perfect sense and explain the way the Java ecosystem lives and functions.

Each version of Java EE includes a set of specifications for various technologies, such as Servlets, JavaServer Pages (JSP), Enterprise Java Beans (EJB), and Java Messaging Service (JMS). Each of these specifications has been defined by an organization called the Java Community Process (JCP). If a person or a group of people decides to propose a specification for some future technology, it creates a Java Specification Request (JSR) and forms a group of experts to work on this specification. JSRs are numbered. For example, the specification for Servlets 3.1 is described in JSR 340.

If you decide to get familiar with any specific JSR, visit the website http://jcp.org. Both Java EE and Java SE implement multiple JSRs. In other words, Java EE is based on standards. If you’d like to see which JSRs are included in Java EE 7, visit http://en.wikipedia.org/wiki/Java_EE_version_history#Java_EE_7_.28June_12.2C_2013.29. This book doesn’t cover all of the JSRs, but it explains some of the main ones. Most importantly, this book tries to show you how to architect Java applications that use the Java EE 7 platform.

Tiers of Java EE Applications

A typical distributed Java application can be divided into three or four logical tiers. (If the application is getting data directly from a DBMS, as described in Chapter 21, it has a two-tier client-server architecture, and Java EE components are not needed.) Figure 25-1 shows selected technologies and some of the ways of building a distributed application that includes Java EE tiers or layers.

image

Figure 25-1: Architecting Java EE applications

Full Java EE Diagram

To see the full Java EE diagram, see the “Profiles” section in the document titled Java Platform, Enterprise Edition (Java EE) Specification, v7.

The client tier can be implemented on a user’s desktop, notebook, mobile phone, or any other device that has embedded JRE or can connect with Java on the web server. Applications that interconnect multiple devices are known as Internet of Things (IoT); they can utilize small sensors with embedded Java and servers that use Java EE technologies. You can create a client as an independent Java application, an applet, or a thin client (an HTML/JavaScript file running in a web browser). The word thin refers to the fact that no business processing (except the input validation) is being done on the client side, so the server has to work hard processing all application logic for all clients, and Java EE shines on the server side.

If you’re building a web application, the web tier (also known as the presentation tier) comes into the picture. You have your choice of JSP, JavaServer Face (JSF), Servlets, or Web Services. These components are responsible for the look of your thin client. Java Swing and JavaFX are oftenused as fat clients working with the server-side applications. The word fat here refers to the fact that the client can contain some business logic, which lowers the load on the server. Any non-graphical user interface (GUI) Java application can be a client of the server-side application created with the help of one or more Java EE technologies.

The business logic of your application is deployed in the business tier, which is represented by EJBs in the Java EE world. In the past EJBs were pretty heavy components and third-party frameworks such as Spring became a popular alternative for implementing the business tier. But Java EE regains its market share in this department because it’s a light POJO- and annotation-based technology that incorporates the best features of the third-party framework. POJO stands for plain old Java object—a Java class that can be written any way you want and doesn’t have to extend any framework class or implement mandatory interfaces.

This term is easily understood by people who witnessed the evolution of EJBs that started with Java classes that had to be written and deployed in a certain convoluted way and accompanied by heavy XML configuration files. Things changed drastically, and now EJBs have turned into POJOs marked with annotations. If for some reason you skipped Chapter 23 on annotations, you should go back and study it; otherwise you won’t understand most of the remaining material in this book.

While drawing the diagram for Figure 25-1, I moved the Web Services box a couple of times between the tiers. On one hand, Web Services (see Chapter 33) are based on web communication protocols; on the other hand they can serve as a façade that hides anything, including an entire legacy application written in COBOL or other languages on mainframes. In the real world, Web Services span all server-side tiers and could even be placed in a separate box in the data tier.

Using DBMSes remains the most popular way to store data in enterprise Java EE applications, but it’s not the only way. The data can be served by an external web service or arrive as a real-time feed from some messaging infrastructure. MOM stands for message-oriented middleware, and you find out what it is in Chapter 30.

Without some practical example, all these new buzzwords may not make much sense to you. You see examples in the upcoming lessons, but for now, I’m just briefly discussing several (not all) ways or re-architecting of the Stock Market application that you’ve seen already implemented with sockets and RMI.

· Have a JavaFX client to connect to StockQuoteServlet, which creates what is known as a session EJB called StockMarketQuote, which connects to external stock exchange software and requests a price quote on the specified symbol(s). This session bean has a timer that updates and sends to the client the price quotes every second.

· Do as described in the previous bullet, but replace the JavaFX application with a thin HTML client.

· The same as before, but replace the Servlet with a JSP.

· The same as before, but replace the JSP with a JSF.

· The same as above, but replace JSF with RESTFul Web Service.

· The same as above, but replace HTTP with WebSocket protocol.

· The same as before, but replace the Web Service with a session EJB that interacts with a message-driven bean (MDB) that subscribes via MOM to the external stock exchange application that sends back new prices only when they change.

· The same as before, but add another session bean that will process every price quote received by MDB and apply a modeling algorithm, and on certain conditions send a message to buy or sell a specific number of shares of the suggested stock to a third-party trading system via a call to a Web Service.

I can keep going. As you can see, there are many ways to design a distributed Java EE application. This is what Java architects do for a living.

Containers Versus Application Servers

Java EE tiers are implemented in containers. Containers contain Java objects. In the Java EE world containers not only contain, but also control the birth, life, and death of Java components. For example, you don’t need to use the new operator to create a new instance of an EJB; the container creates a pool of them based on configuration parameters. Basically, a container is an area inside JVM that can support a life cycle of certain types of Java objects, such as servlet, EJB, and so on. The word container applies to clients too; for example, Java SE run time serves as a container for Java client applications.

Containers perform useful functions, and one of them is thread safety. It’s great that multiple clients can connect and make requests to the same server, but can you be sure that a thread initiated by Mary won’t interfere with John’s thread? An EJB container implements a single-threaded model ensuring that each client’s request operates in a dedicated thread. Containers may offer transactional support with Java Transaction API (JTA) and persist data for you with Java Persistence API (JPA).

In the first few lessons I used a blueprint analogy to explain the relationship between Java classes and objects. I’m using this analogy again, but this time I’m explaining the relationship between the Java EE specification and application servers. The Java EE is a specification, and when its release is published, vendors who want to implement it in their software products create application servers that support this specification.

Multiple vendors offer their versions of a Java EE application server. The question is what version of the Java EE specification they support. Currently four application servers—GlassFish (Oracle), WildFly (Red Hat), WebLogic (Oracle), and Tmax JEUS (TMaxSoft)—support Java EE 7. To see the latest list of servers that support Java EE 7 visit the Java EE Compatibility web page.

Java EE application servers have to support multiple containers; for example, a Servlet container and an EJB container. Some vendors prefer to create products supporting only certain technologies defined in the Java EE specification. For example, Tomcat (Apache Foundation), Jetty (Eclipse Foundation), and Resin (Caucho) offer support for selected technologies (such as Servlets and JSP), which makes them suitable for implementing web applications, but if you are planning to create web applications based on one of these products, you need to figure out what other tools or frameworks are needed to support transactions, the business tier, data persistence, and more. TomEE (Apache Foundation) supports Servlets, JSP, EJB, and other Java EE technologies.

This book uses GlassFish 4.1 from Oracle, which is fully compliant with Java EE 7. I have selected the most widely used technologies in Java EE development today. In particular you’ll be learning about the following:

· Java Servlets (JSR 340)

· JavaServer Pages (JSR 245)

· Enterprise Java Beans (JSR 345)

· Java Persistence API (JSR 338)

· Context and Dependency Injection (JSR 346)

· Java Message Service (JSR 343)

· Java API for RESTFul Web Services (JSR 339)

· Java API for JSON Processing (JSR 353)

· Java API for WebSocket (JSR 356)

You may feel overwhelmed with all these terms, but I try to explain them in easy-to-understand language.

Profiles and Pruning

Although Java EE offers a full stack of server technologies, most of the real-world applications don’t need all of them. In the past, to get Java EE certified, a vendor of an application server had to implement all JSRs that were listed in the Java EE specification. But most of the applications don’t use all technologies included in the full Java EE specification. This is how that concept of a profile came about. A profile is a preconfigured subset of Java technologies geared toward solving a specific type of application. Currently, besides the full profile, there is the Web Profile, which is designed specifically for the development of web applications. The Web Profile defines required components (for example, Servlets, JSF, JSP, CDI, EJB Lite, JPA, JTA), but vendors may include technologies from the full Java EE specification, too. In the future, new profiles may be created to address specific needs of developers.

Java SE Profiles

Java SE 8 also has profiles. So-called compact profiles were introduced to offer configurable lightweight run-times for small devices with embedded Java.

Pruning is a way to reduce the size of the Java EE platform. The pruning process starts with marking in JavaDoc the technologies that are candidates for removal. Then, based on the reaction of the Java community, they will be either removed from the future specifications or not. It’s up to the application server vendor to define the process of removal, but it’s done carefully so the existing application won’t break. Some of the technologies (such as JAXR 1.0) are optional for implementation in Java EE 7 servers.

Why Java EE?

You may say, “I want my RMI-based stock server application back. Why make things so complex?” The reason is that a single instance of UnicastRemoteObject in your RMI StockServer may need to process tens of thousands of concurrent user requests. Because of this you’ll need to write code ensuring that such concurrent processing is thread safe.

Servlet and EJB containers are scalable, and they take care of all multithreading issues, enabling you to write application code as if the application were the only user! This alone should be a good reason for using the Java EE stack as opposed to RMI. Without going into a detailed comparison between RMI and other Java EE technologies, I’ll just add that if you need to deploy your StockServer application on the web, corporate firewalls may not allow clients to open certain ports and use the JRMP communication protocol required by RMI.

Java EE and Multithreading

One of the major changes in Java EE 7 compared to previous versions is that you are allowed to introduce multiple threads in your application code that run inside Java EE containers. It was not allowed before—only the container could create and manage threads. Now with the help of such classes as ManagedExecutorService and ManagedThreadFactory you can create threads from your code, too.

Java EE is a very robust, reliable, and scalable platform and you will appreciate what its container will do for your code. This section mentions a couple of concepts.

If you want Java EE containers to help you, help them by providing configuration parameters (annotations) that specify how many instances of the same session bean StockMarketQuote you want pre-created for you by the EJB container. Each of these session beans may be “rented” from a pool to the client’s request, and then put back. How many beans do you need? I don’t know. It depends on the load on your system—the number of concurrent (simultaneous) requests for price quotes that have to be supported by your system.

Java EE implements dependency injection. An object doesn’t have to reach out to get the resources it needs because the container can inject its resources (and your code can inject application objects) into your object using annotations. You see examples of CDI later in the book.

WebSocket protocol allows you to switch from the request-response-based communications typical in web applications to a simultaneous two-way data exchange between the client and server. The server can initiate data push without waiting for the client requests. Consequently, creating real-time web applications becomes a lot easier.

JSON stands for JavaScript Object Notation. JSON became a de facto standard data format used in data communication between web browsers and servers. Java EE 7 defines a standard way of generating and parsing JSON data.

Interceptors offer a mechanism by which containers can intercept methods invoked on your session beans. When the call is intercepted, you can specify additional code to be called before or after the method is executed. For example, imagine that you need to add logging before certain methods are called. Adding interceptors is an easy way to do this.

Messaging allows you to introduce asynchronous processing into the business workflow of your application. Instead of making direct requests to business objects of your application, your code can place messages into queues maintained by special servers—Message-Oriented Middleware (MOM).

Starting in Lesson 26 you have a chance to apply these concepts and features. Oracle published a complete Java EE 7 Tutorial that covers each and every technology in detail. The tutorial uses GlassFish server, and this book uses it, too.

Java EE Code Samples

More than 200 code samples illustrating various Java EE 7 technologies are available at https://github.com/javaee-samples/javaee7-samples.

Try It

This lesson was a high-level overview of the Java EE 7 platform. The hands-on exercises starting in the next lesson require that you have an application server installed, and installing the GlassFish server is your next assignment.

Lesson Requirements

You should have Java installed.

Step-by-Step

One instance of the GlassFish server may run several domains, and domain1 is the default. The command to stop a domain looks similar, but instead of using the command start-domain use stop-domain.

1. Download GlassFish Server Open Source Edition. At the time of this writing the latest version, GlassFish 4.1, is available at the following URL: https://glassfish.java.net/download.html.

2. Download and unzip the file titled Java EE Full Platform.

3. In the command (or Terminal) window switch to the directory glassfish4/bin. If you use Mac OS, start the server using the following command:

4. ./asadmin start-domain domain1

Windows users start the server using the following command:

asadmin.bat start-domain domain1

On my computer after starting GlassFish the Terminal window looked like Figure 25-2.image

Figure 25-2: Starting GlassFish from the Terminal window in Mac OS

5. By default GlassFish Server runs on port 8080 and the port for server administration is 4848. Open your web browser and enter http://localhost:8080—you should see the GlassFish welcome page.

6. Open the GlassFish administration console by entering in your browser http://localhost:4848. The web browser should display the window shown in Figure 25-3.image

Figure 25-3: The GlassFish admin console

7. Download the Oracle GlassFish Server Quick Start Guide from https://glassfish.java.net/docs/4.0/quick-start-guide.pdf for a description of the administrative commands for working with the GlassFish server.

TIP Please select the videos for Lesson 25 online at www.wrox.com/go/javaprog24hr2e. You will also be able to download the code and resources for this lesson from the website.