Over a million developers have joined DZone.
{{announcement.body}}
{{announcement.title}}

Java EE 8 and the Open Future of Java EE

DZone's Guide to

Java EE 8 and the Open Future of Java EE

Take a look at the new tools that came with Java EE 8, see how the transition to Jakarta EE is going, and what the future holds for enterprise Java.

· Java Zone ·
Free Resource

Download Microservices for Java Developers: A hands-on introduction to frameworks and containers. Brought to you in partnership with Red Hat.

This article is featured in the new DZone Guide to Java: Features, Improvements, & Updates. Get your free copy for more insightful articles, industry statistics, and more!

Java EE 8 has been released and includes a significant amount of changes relevant to server-side Java developers. This article will overview these changes at a high level and look at some representative code examples.

A unique characteristic of Java EE 8 is that it has been one of the most community opinion-driven major technology releases in the history of Java. The scope of Java EE 8 was determined by two separate developer surveys: one conducted before Java EE 8 development started and one toward the end of when Java EE 8 was released. As a result, Java EE 8 is a very feature-complete release, particularly for applications that don't need fine-grained microservices features.

Nonetheless, such features have already been brought to the Java EE ecosystem through the MicroProfile initiative and will likely be standardized as part of the next major release of Java EE as Jakarta EE 9.

Themes

Let's briefly look at the distinguishable themes for Java EE 8 before diving into feature details.

  • Web standards alignment

  • HTTP/2, SSE, JSON

  • CDI alignment

  • CDI 2, JSF managed bean pruning, injecting JSF artifacts, CDI support in JPA

  • Simplicity

  • Security, EJB pruning

  • Java SE 8 alignment

  • JSF, JPA, JAX-RS, JMS, Bean Validation, JSON-P, CDI

Servlet 4

The principal goal of Servlet 4 is to bring HTTP/2 support to server-side Java. HTTP/2 is a fundamental modernization of the protocol that keeps the internet together.

Because these are largely protocol layer changes, they can be transparently handled by the Servlet 4 runtime without any API changes. The Servlet 4 certification tests that a container properly implements HTTP/2. This is very important since no other

certification process for HTTP/2 exists. Servlet 4 does introduce a simple API change to enable server-push. However, even this change is transparently absorbed at a lower level in the case of JSF 2.3 users.

JSON-B (Java API for JSON Binding)

Making JSON a first-class citizen of the platform has been a goal since Java EE 7. Using JSON should not require installing or configuring yet another library. To that end, a low-level parsing API called JSON-P (Java API for JSON Processing) was introduced in Java EE 7. Java EE 8 introduces a higher-level JSON binding API called JSON-B that makes it feel like JSON is as native as Java serialization in Java EE.

The idea is that converting POJOs to/from JSON should just work by default without needing to add any annotations. JSON-B does include a small number of annotations to override default mappings such as @JsonbProperty (to rename fields) and @JsonbTransient (for fields to be ignored by serialization).

The example below shows these concepts in action.

@GET ...
@Produces("application/json")
public Person getPerson(...) {
    ...
    Person duke = new Person();
    duke.setName("Duke");
    duke.setGender("Male");
    phones = new HashMap<>();
    phones.put("home", "650-123-4567");
    phones.put("mobile", "650-234-5678");
    duke.setPhones(phones);
    return duke;
}


In the example above, the Person POJO does not have any JSON-B annotations. Because JAX-RS 2.1 integrates with JSON-B in Java EE 8, the Person POJO will be automatically converted to the JSON below in the HTTP response since the output is specified to be of type application/json.

{
    "name":"Duke",
    "gender":"Male",
    "phones":{
        "home":"650-123-4567",
        "mobile":"650-234-5678"
    }
}


JSON-P 1.1

JSON-P was fairly feature-complete in Java EE 7. In Java EE 8 JSON-P incorporated updates in the JSON standards space such as JSON-Pointer, JSON-Patch, and JSON-Merge/Patch.

JSON-Pointer allows for looking up values in a JSON structure using a URL-like path. JSON-Patch allows for issuing commands to modify parts of a JSON structure. JSON-Patch depends on JSON-Pointer to reference locations in a JSON structure. JSONMerge/Patch is similar to JSON-Patch but offers capabilities to do sophisticated merges and diffs of JSON structures.

The best way to explore these features is through a simple example.

Let's start with the following JSON structure:

[
    {
        "name":"Duke",
        "gender":"Male",
        "phones":{
            "home":"650-123-4567",
            "mobile":"650-234-5678"
        }
    },
    {
        "name":"Jane",
        "gender":"Female",
        "phones":{
            "mobile":"707-555-9999"
        }
    }
]


The following shows how using two JSON-Patch commands to modify the above JSON structure looks. The first command updates the mobile phone number for "Duke". The second command removes "Jane" from the list of persons. /0/phones/mobile and /1 are examples of JSON-Pointers.

Aside from replace and remove, JSON-Patch supports operations like add, move, copy, and test.

[
    {
        "op":"replace",
        "path":"/0/phones/mobile",
        "value":"650-111-2222"
    },
    {
        "op":"remove",
        "path":"/1"
    }
]


The following is how the JSON-P 1.1 code to apply these JSONPatch operations looks. The target object holds the JSON-P structure for the persons array.

JsonPatchBuilder builder = new JsonPatchBuilder();
JsonArray result = builder
    .replace("/0/phones/mobile", "650-111-2222")
    .remove("/1")
    .apply(target);


SSE (Server-Sent Events)

SSE is part of HTML5. SSE allows for server-to-client streaming of events over HTTP. Under the hood, SSE is a long-lived HTTP connection that uses a specialized content-type: text/eventstream. Events are typically distinct JSON objects sent from the server to the client over time. SSE is useful for "stock ticker"-type applications and monitoring consoles. SSE is supported both on the server and client side in JAX-RS 2.1. The following is a server-side example:

@Path("tickers")
public class StockTicker {
    @Resource ManagedExecutorService executor;
    @GET @Produces("text/event-stream")
    public void getQuotes(
        @Context SseEventSink sink,
        @Context Sse sse) {
        executor.execute(() -> {
            ...
            sink.send(sse.newEvent(stockqoute));
            ...
        });
    }
}


In the example, a browser connects to the server using the "tickers" endpoint. The endpoint produces a series of stock quote updates in a background thread and sends them to the client over an SSE event sink connection pipe using the Sse event builder utility.

Java EE Security

The goal of the new Java EE Security API is to make common, simple security needs portable by introducing embeddable authentication and authorization via annotations and CDI. At a high level, three new features are introduced:

  1. It is possible to specify through simple annotations whether the application uses basic, form-based, or custom authentication.

  2. It is possible through simple annotations to specify that authentication and authorization data are stored in the database or LDAP directory. If the built-in identity stores are not enough, it is possible to have a simple CDI bean in the application act as an identity store.

  3. A universal security context is made available through CDI injection. This context provides a handle to information about the currently logged-in user that can be used anywhere including in custom security interceptors. This is in addition to the existing @RolesAlllowed annotation.

The following annotation example that specifies database security is illustrative of just how simple Java EE 8 security is.

@DataBaseIdentityStoreDefinition(
        dataSourceLookup = "java:global/MyDB",
        callerQuery = "SELECT password FROM principals
        WHERE username = ? ",
        groupsQuery = "SELECT role FROM roles where
        username = ? ", ...)


CDI 2

One of the key changes in CDI 2 is the standardization of a bootstrap mechanism in plain Java SE environments. This has meant breaking CDI into three parts: core, Java SE, and Java EE. These changes enable CDI to be adopted by more technologies — inside and outside of Java EE. These changes have enabled CDI to be used as a core technology for the MicroProfile initiative. Another key change in CDI 2 is making events completely asynchronous. The following example shows the feature.

@Inject @CargoInspected Event <Cargo> cargoInspected;
...
public void inspectCargo(TrackingId trackingId) {
    ...
    cargoInspected.fireAsync(cargo);
}
public void onCargoInspected(
        @ObservesAsync @CargoInspected Cargo cargo) {


The inspectCargo method thread gets control back immediately after the fireAsync method is invoked. The onCargoInspected observer method is invoked on a completely separate thread.
CDI 2 also made several simplifications to its extensibility APIs to further encourage the CDI plugin ecosystem. Lastly, CDI 2 adapts to Java SE 8 features such as lambdas, completable futures, streams, and repeatable annotations.

Beyond the changes in CDI 2 itself, a number of technologies improved their alignment with CDI in Java EE 8. For example, JSF 2.3 makes key artefacts like the FacesContext injectable and deprecates its own older managed bean model in favor of CDI.

JPA 2.2 also improved its alignment with CDI by making artefacts like attribute converters injection-capable.

A key piece of CDI alignment had been slated for Java EE 8 through JMS 2.1. JMS 2.1 aimed at creating a CDI-based JMS listener to replace EJB message-driven beans. Similarly, EJB annotations like @Asynchronous and @Schedule could be made available to all CDI beans through the Java EE Concurrency Utilities. Unfortunately, Oracle decided to discontinue this work for Java EE 8. This is likely work that will be done in the next major Java EE revision.

Fortunately, some work towards deprecating EJB was done in Java EE 8 such as pruning CORBA interoperability.

Repeatable Annotations

Prior to Java SE 8, it was not possible to repeat annotations. As a result, where annotations needed to be repeated, Java EE used wrapper annotations, as shown below:

@NamedQueries({
    @NamedQuery(name = SELECT_ALL, query = "..."),
    @NamedQuery(name = COUNT_ALL, query = "...")
})
public class Customer {


As of Java SE 8, such annotations have been adapted to be repeatable, as shown below.

@NamedQuery(name = SELECT_ALL, query = "...")
@NamedQuery(name = COUNT_ALL, query = "...")
public class Customer {


The technologies in Java EE 8 that have adapted to repeatable annotations include JPA, JMS, JavaMail, Bean Validation, EJB, and CDI.

Date-Time API

The new Java SE 8 date-time API is more feature-complete, easy-to-use, and internationalized compared to the older Java SE date handling functionality. As the following example shows, both JPA 2.2 and Bean Validation 2 have been updated to natively support the date-time API.

@Entity
public class Accident {
    ...
    @Temporal(TemporalType.TIMESTAMP)
    @Past
    private Instant when;
    ...
}


JPA 2.2 knows how to properly read the when field of type Instant from the database and write it back. Similarly, all Bean Validation 2 annotations correctly validate date-time API types. JSF 2.3 can also correctly convert and validate all date-time types without any additional code.

Completable Future

Java SE 8 completable futures bring JavaScript promises to Java. Compared to the older Java SE Future interface, completable futures are non-blocking, lambda-friendly, and composable.

These characteristics tend to be very important while asynchronously invoking interrelated RESTful endpoints that are part of a microservices-based system.

These are the reasons the JAX-RS 2.1 client API has been adapted to make use of completable futures. The following example shows the feature.

CompletionStage <Assets> getAssets = client
    .target("assets/{ssn}")
    .resolveTemplate("ssn", person.getSsn())
    .request("application/json")
    .rx()
    .get(Assets.class);
CompletionStage <Liabilities> getLiabilities = client
    .target("liabilities/{ssn}")
    .resolveTemplate("ssn", person.getSsn())
    .request("application/json")
    .rx()
    .get(Liabilities.class);
Coverage coverage = getAssets.
thenCombine(getLiabitities,
        (assets, liabilities) -> underwrite(assets,
            liabilities))
    .toCompletableFuture().join();


Streams

Java SE 8 streams utilize lambdas to provide high-performance, concise aggregate operations on collections of objects. Operations include filter, transform, sum, average, min, max, and sort.

JPA 2.2 query results can now return streams. The following example shows the feature.

Stream<Book> books = entityManager.createQuery(
   "SELECT b FROM Book b", Book.class).
getResultStream();
books.map(b -> b.getTitle() + " was published on " +
b.getPublishingDate())
   .forEach(s -> log.info(s));


JSON-P 1.1 was also adapted to easily convert between JSON arrays and streams.

Aside from these headline features, Java EE 8 contains a lot more that you should look into yourself. For example, CDI 2 can now order events, JSF 2.3 provides an easy way to use WebSocket, JAX-RS 2.1 allows for broadcasting SSE events to multiple clients, Bean Validation 2 adds new constraints like @Email, @NotEmpty, @NotBlank, @Positive, @Negative, and much more.

MicroProfile, Jakarta EE, and the Future of Java EE

The MicroProfile initiative was started at the Eclipse Foundation parallel to Java EE 8 to bring features required for fine-grained microservices into the Java EE ecosystem. MicroProfile is simply an open-source project led by Java EE vendors, is not a true open standard and thus can move much faster. MicroProfile recently had a 1.3 release and already enables features like fat-jars, dynamic configuration, circuit-breakers, fault-tolerance, healthchecks, metrics, JWT, OpenAPI/Swagger, distributed tracing and type-safe REST clients.

The Eclipse Foundation also has a project named JNoSQL that aims to standardize NoSQL database access for Java, much like JDBC. All of these features are likely to be standardized as part of the next major revision of Java EE.

In addition to announcing the release of Java EE 8, Oracle also announced that it is donating all Java EE code to the Eclipse Foundation. Going forward, Java EE will be renamed to Jakarta EE and will no longer be owned by any single commercial entity.

It is expected that Jakarta EE 8 will be released later in the year with a fully open-source version of Java EE, including a completely open-source set of certification tests as well as an open-source governance process to replace the JCP. Jakarta EE 9 — including significant new features — is expected to be released in 2019.

This article is featured in the new DZone Guide to Java: Features, Improvements, & Updates. Get your free copy for more insightful articles, industry statistics, and more!

Download Building Reactive Microservices in Java: Asynchronous and Event-Based Application Design. Brought to you in partnership with Red Hat

Topics:
java ,java ee 8 ,json-b ,json-p ,jakarta ee ,tutorial

Opinions expressed by DZone contributors are their own.

{{ parent.title || parent.header.title}}

{{ parent.tldr }}

{{ parent.urlSource.name }}