My picks for Java EE track @ JavaOne 2016

Its time for JavaOne 2016 with a great line up of Java EE talks… Here are my favorite picks, filed into three categories. You should definitely consider attending few of these if you are one of the lucky JavaOne attendees !🙂

  • Java EE 8 – covers evolution of Java EE 8 in general along with talks targeted at the upcoming specifications (new, updated)
  • Java EE Microservices – these talks focus on how microservices based applications can be built using Java EE specifications
  • General – any other talk focusing on Java EE 7 or specific Java EE APIs

Please note that there are other Java EE talks as well and the ones listed here just happen to be my favorites and reflect my personal opinion only

Java EE 8

  • Java EE 8 Update – what’s been done, shift in focus, JSRs (new and current)
  • Java EE for the Cloud – discussions, feedback with Java EE spec leads
  • What’s Next for Enterprise Java? – A key discussion platform where panelists (including key Java EE architects and leaders from the enterprise community) will weigh in on directions they think enterprise Java should take
  • JAX-RS 2.1 for Java EE 8 – new features like CDI integration, SSE, NIO etc.
  • Java EE Next: HTTP/2 and REST Opportunities – what can Java EE 8 offer in these areas…
  • Security for Java EE 8 and the Cloud – revolves around JSR 375..
  • Servlet 4.0: Status Update and HTTP/2 Comes to Java EE 8 – how can it help in the ‘modern’ cloud era ?
  • JCache and Java EE: Bridging the Gap – technical aspects of  plugging JCache into JavaEE 8
  • What’s New in the Java API for JSON Binding – latest status from JSR 367 and including a deep dive exploration
  • Configuration for Java EE 8 and the Cloud – defining a cloud-ready Java EE based configuration standard

Java EE Microservices

  • Migrate Java EE Applications to Microservices and Oracle Java Cloud
  • Live-Coding No-Ceremony Microservices – hacking on nano services with Adam Bien using Java EE
  • Run Your Java EE Apps with WildFly Swarm in Oracle Application Container Cloud – how Wildfly Swarm can make Java EE 7 apps awesome in Oracle Application Container Cloud
  • Cloud-Native Java EE – 12 factor apps with Java EE …
  • BootEE: Creating Lightweight Services with Java EE – what are your options ?

General (Java EE 7 & others)

  • Java EE, Extendable to Functional – never ever miss a David Blevins session! this one is covers CDI scopes, JCA (Java EE 7) along a discussion of functional programming paradigms apply to Java EE (both 7 and maybe even v8)
  • Java EE Applications on Oracle Java Cloud Service – the title says it all
  • REST in Peace with Java EE : a real world Java EE 7 story about REST API implementation for Dataverse
  • Second-Level Cache in JPA Explained: self evident I guess..
  • Java EE 7 Meets Java 8: learn how to leverage Java 8 for Java EE 7 apps (powered by live coding)
  • Java EE: Beyond the Basics – get hands on with intermediate & advanced Java EE 7 features
  • Top 50 Java EE 7 Best Practices – as per title, fortified with code samples

You might want to check out


Posted in Java EE | Leave a comment

JSON-B test drive using JAX-RS

This is a quick post about JSON-B specification which is due in Java EE 8. It’s main purposes are

  • Provide JSON binding i.e. marshalling and un-marshalling to and from Java objects
  • Eclipselink will server as Reference Implementation
  • Supports Java object model to JSON mapping via annotations
  • Supports default mapping for implicit transformations b/w Java model and JSON (without annotation/additional metadata)
  • Produce JSON schema from Java classes
  • Support further customization of default mapping mechanisms as well as partial mapping (part of JSON doc needs to be mapped to Java model)
  • Will integrate with JSON-P and probably with JSON API JEP 198 (Java SE API for JSON processing) if needed

Please note that

  • this is just a quick test of the JSON-B implementation in a Java EE 7 container
  • not an ideal scenario i.e. it does not demonstrate integration of the JSON-B spec with a Java EE container (at least not yet)
  • I am not aware of Java EE 8 builds which ship with JSON-B implementation as of now

From a (Java EE 8) container integration perspective (near future)

the integration should/will be seamless and transparent – the way it is in case of JSON-P and JAXB annotated classes i.e.

  • you will ideally be able to annotate your Java classes using JSON-B annotations and
  • expect them to get serialized/deserialized automatically by the container (e.g. JAX-RS runtime) automatically

Overview of what was done

  • Have a simple POJO
  • Expose POJO using JAX-RS (GET, POST)
  • Use JAX-RS Message Body Reader and Writer – this overrides the default JSON-P providers and leverage JSON-B API here (simply use the default mapping feature) for transformation
  • Repeat the same for a ‘List of’ POJOs

Github project available here – this is not a Maven project. Ideally, you would want to clone into NetBeans, build and run on a Java EE 7 container. Make sure to have RI JAR in WAR (details below)

To be noted

  • I could not grab the Maven artifact of the JSON-B API JAR (maybe I am missing something), so ended up including the JSON-B API sources in the WAR itself
  • Same case with the RI – Downloaded it directly from here

More than this example, what’s important is the following


Posted in Java, Java EE | Tagged , , , , , , | Leave a comment

Nuances of JAX-RS client side async callback

Going async with JAX-RS

JAX-RS provides client side asynchronous behavior to complement its server side counterpart. It’s powered by the AysncInvoker interface – the best part if that you do not need to get hold of it explicitly. The fluent JAX-RS client API makes it available by including the async() call in your builder calls

e.g. ClientBuilder.newClient().target(“”).request().async().get

Like every other asynchronous offering, the JAX-RS client API offers you a couple of options to manage async calls

  • DIY (do-it-yourself) – get back a Future instance and work with it to track the result
  • Declarative callbacks – let the API know what you want it to do in case of a success or failure

Declarative callbacks

A callback is required to implement the InvocationCallback interface. It defines two methods

  • completed: gets called when an invocation successfully finishes. The result response is passed as a parameter to the callback method.
  • failed: it is invoked in case of a failure

Here is an example

There is more to failure scenarios than meets the eye

The invocation of the failed method happens only in case of a failure – no doubts there. But there is a caveat – the criteria is based on the generic entity type (Java class type to be specific) of the response from the server.

Here is an example for the normal scenario

When the response type is anything other than

In case of a server side error (e.g. HTTP 404), the failed method is invoked

What if the generic type if

In such scenario, the completed method is invoked – that’s the catch! You can always investigate the actual HTTP response by calling the getStatus method (as demonstrated in the below example)

At the outset, it might look odd ….

but think about it – you were expecting a response from the service and you did get one (it does not matter if it was success/failure). From the framework’s perspective, only if the API call to the endpoint failed to go through i.e. there was a client side error during invocation, should the failed method should be called. This is an important distinction/caveat which one should make a note of…

Further reading


Posted in Java, Java EE | Tagged , , , | Leave a comment

Java Websocket containers: the possibilities

The Java Websocket API (JSR 356) specification supports different containers

  • Good old Java EE 7 app servers – since Websocket API is integrated directly into the Java EE 7 Platform
  • Servlet 3.1 containers
  • Standalone containers – for runtimes which are not servlet complaint

Hello Tyrus !

Tyrus is the reference implementation for Java Websocket API

  • What’s important to understand is that it’s the implementation of the Websocket specification i.e. it provides both Server and Client side support for building Websocket applications using the standard JSR 356 APIs
  • It’s not an out-of-the-box container i.e. does not have a runtime as such

So, how does Tyrus support the above mentioned runtimes ?

Here is how

  • Tyrus has a modular architecture i.e. it has different modules for server, client implementations, a SPI etc.
  • It has the concepts of containers (you can think of them as connectors) for specific runtime support (these build on the modular setup)

Tyrus containers

Servlet container a.k.a tyrus-container-servlet

  • Used to integrate with existing Servlet 3.1 containers
  • Leveraged to plug into the Web (Servlet) Container in Java EE 7 compliant app servers

Standalone container

You have two options

Grizzly Container (tyrus-container-grizzly module)

  • This is achieved with Grizzly (which provides the runtime)
  • Can be used for server or client (or both) modes as per your requirements

Here are the Maven dependencies

Here is the Websocket (annotated) endpoint

Here is how to start it (embedded)

Pure JDK container (tyrus-container-jdk-client module)

  • Client only mode
  • Vanilla JDK i.e. no additional dependencies
  • Leverages JDK 1.7 non-blocking I/O (Asynchronous Channel)

Maven dependencies

The (annotated) client endpoint

Client code to connect to Websocket endpoint (outlined above)



Posted in Java EE | Tagged , , , , , | Leave a comment

Notes on JPA L2 Caching

Here are some notes on L2 (level 2/shared) cache in JPA

Quick facts

  • JPA L2 cache was standardized in JPA 2.0 (Java EE 6)
  • Based on EntityManagerFactory i.e. its a global cache common across all Persistence Units
  • A layer which site between the L1 cache (EM) and the database i.e. the database is queried only if the entity is not in the L1 cache and L2 cache
  • This feature is optional (but most of the well known providers support it)

Initial setup

@Cacheable: this annotation is used to declaratively configure L2 (shared) caching for a JPA entity

Cache Modes

Specified in persistence.xml or during Entity Manager Factory creation (programmatic)

  • NOT_SPECIFIEDdefault mode. Provider specific behavior (e.g. Eclipselink uses L2 cache by default vs Hibernate which needs explicit configuration for the same)
  • ENABLE_SELECTIVE – only entity classes with @Cacheable(true) are cached
  • DISABLE_SELECTIVE – entity classes with @Cacheable(false) are not cached
  • ALL – all the JPA entities are cached
  • NONE – none of the entities are cached

A JPA persistence.xml demonstrating usage of L2 caching config parameter

Here is a simple JPA entity with explicit L2 caching metadata

Override mode

In addition to the basic configuration options specified above, JPA allows you to dynamically specify how you want to interact with the L2 cache. These options are available for the entities which have been explicitly configured to participate in L2 caching

They can be enforced using the following methods

  • Entity Manager property
  • find method of Entity Manager
  • hint during query execution

Read options

These options come into play during reading/fetching data from the cache and can be specified using the javax.persistence.cache.retrieveMode property

  • CacheRetrieveMode.USE: read from L2 cache
  • CacheRetrieveMode.BYPASS: skip the cache (refer the database directly)

Indicate L2 cache usage via EM property

Write options

These options are used to configure operations related to putting data into the cache and can be specified using the javax.persistence.cache.storeMode property

  • CacheStoreMode.USE: populate the cache in response to the executed operation
  • CacheStoreMode.BYPASS: do not modify the cache contents post operation
  • CacheStoreMode.RERESH: to be used when your database is affected by external sources other than your application itself. Using this option forces the JPA provider to skip the cache (during fetch), go to the database and populate the result into the cache (effectively, a refresh operation)

NoteCacheRetrieveMode and CacheStoreMode are enums

Explicit L2 cache overrides using EM and query hints

Other stuff . . .

Other L2 cache related methods exposed by the javax.persistence.Cache interface (these are self explanatory)

  • contains: is this entity in the L2 cache ?
  • evict: remove this entity from the cache
  • evictAll: clear the shared cache

Interrogating the JPA L2 cache


Posted in Java EE | Tagged , , , , | 5 Comments

Hybrid queries with JPA 2.1

Before JPA 2.1

There were two types of queries

  • Named (static): these are declared using the @NamedQuery or @NamedQueries annotations.
  • Dynamic: as the name suggests, this type of query is specified by the application logic at runtime

JPQL, Native SQL as well as Stored Procedure based queries support above mentioned modes and each one of them have their own pros and cons

JPA 2.1 supports

the notion of a hybrid style query wherein you can

  • declare a query in the code (as a regular string)
  • bind it to the EntityManagerFactory
  • use it as a regular Named Query

Predominant use case

Useful when a query has the following properties

  • It needs to be executed repeatedly (this one is obvious), and
  • Cannot be pre-determined (else @NamedQuery would have sufficed !) i.e. it depends on run time information


Although it incurs a (one time) processing overhead, after that, it offers the same benefits as a regular named query i.e. does not need to be processed by the JPA provider repeatedly. This is obviously not the case with dynamic JPQL queries which need to processed by the provider (converted to SQL) prior to execution

Further reading


Posted in Java EE | Tagged , , , , , , | Leave a comment

New eBook: REST assured with JAX-RS

I am happy to announce the release of yet another book – REST assured with JAX-RS:-)

To download …

Just visit the book page and click the Add Ebook to Cart button. Don’t worry, the book is absolutely free !:-)


Quick preview

It’s structured into distinct sections

  • Warm up: Gives you an idea of what the book is about, what you can expect, JAX-RS & REST introduction
  • Section I: Deals with the basics and covers topics such as Resources, HTTP mapping, HTTP Injection, Client API and Security
  • Section II: Dedicated to Providers – Message Body Readers & Writers, Filters, Interceptors, Exception Mappers and associated topics
  • Section III: Covers slightly advanced topics such as request pipeline, caching, content negotiation etc
  • Miscellaneous: The last portion of the book covers Asynchronous APIs and the future version

Hope you enjoy it ! Feedback, comments, suggestions are always welcome


Posted in Java EE | Tagged , , , | 2 Comments

JPA Entity Manager API notes

Bare basic stuff…

  • Categorizes JPA Entity Manager operations
  • Good for quick glance

Persistence Context Operations

CRUD operations

  • <T> T find(java.lang.Class<T> entityClass, java.lang.Object primaryKey)
  • <T> T find(java.lang.Class<T> entityClass, java.lang.Object primaryKey, LockModeType lockMode)
  • <T> T find(java.lang.Class<T> entityClass, java.lang.Object primaryKey, LockModeType lockMode, java.util.Map<java.lang.String,java.lang.Object> properties)
  • <T> T find(java.lang.Class<T> entityClass, java.lang.Object primaryKey, java.util.Map<java.lang.String,java.lang.Object> properties)
  • <T> T merge(T entity)
  • void persist(java.lang.Object entity)
  • void remove(java.lang.Object entity)

other operations

  • void refresh(java.lang.Object entity)
  • void refresh(java.lang.Object entity, LockModeType lockMode)
  • void refresh(java.lang.Object entity, LockModeType lockMode, java.util.Map<java.lang.String,java.lang.Object> properties)
  • void refresh(java.lang.Object entity, java.util.Map<java.lang.String,java.lang.Object> properties)
  • void flush()

  • void clear()

  • void detach(java.lang.Object entity)
  • boolean contains(java.lang.Object entity)

Operations on self

  • void close()
  • boolean isOpen()

Query Operations

  • Query createNamedQuery(java.lang.String name)
  • <T> TypedQuery<T> createNamedQuery(java.lang.String name, java.lang.Class<T> resultClass)
  • StoredProcedureQuery createNamedStoredProcedureQuery(java.lang.String name)
  • Query createNativeQuery(java.lang.String sqlString)
  • Query createNativeQuery(java.lang.String sqlString, java.lang.Class resultClass)
  • Query createNativeQuery(java.lang.String sqlString, java.lang.String resultSetMapping)
  • Query createQuery(CriteriaDelete deleteQuery)
  • <T> TypedQuery<T> createQuery(CriteriaQuery<T> criteriaQuery)
  • Query createQuery(CriteriaUpdate updateQuery)
  • Query createQuery(java.lang.String qlString)
  • <T> TypedQuery<T> createQuery(java.lang.String qlString, java.lang.Class<T> resultClass)
  • StoredProcedureQuery createStoredProcedureQuery(java.lang.String procedureName)
  • StoredProcedureQuery createStoredProcedureQuery(java.lang.String procedureName, java.lang.Class… resultClasses)
  • StoredProcedureQuery createStoredProcedureQuery(java.lang.String procedureName, java.lang.String… resultSetMappings)
  • CriteriaBuilder getCriteriaBuilder()

Entity Graph operations

  • <T> EntityGraph<T> createEntityGraph(java.lang.Class<T> rootType)
  • EntityGraph<?> createEntityGraph(java.lang.String graphName)
  • EntityGraph<?> getEntityGraph(java.lang.String graphName)
  • <T> java.util.List<EntityGraph<? super T>> getEntityGraphs(java.lang.Class<T> entityClass)

Transaction operations

  • <T> T getReference(java.lang.Class<T> entityClass, java.lang.Object primaryKey)
  • EntityTransaction getTransaction()
  • boolean isJoinedToTransaction()
  • void joinTransaction()

Lock operations

  • void lock(java.lang.Object entity, LockModeType lockMode)
  • void lock(java.lang.Object entity, LockModeType lockMode, java.util.Map<java.lang.String,java.lang.Object> properties)


  • java.lang.Object getDelegate()
  • EntityManagerFactory getEntityManagerFactory()
  • FlushModeType getFlushMode()
  • LockModeType getLockMode(java.lang.Object entity)
  • Metamodel getMetamodel()
  • java.util.Map<java.lang.String,java.lang.Object getProperties()
  • void setFlushMode(FlushModeType flushMode)
  • void setProperty(java.lang.String propertyName, java.lang.Object value)
  • <T> T unwrap(java.lang.Class<T> cls)

Posted in Java EE | Tagged , , , | Leave a comment

Custom Security Context in JAX-RS

And the JAX-RS juggernaut continues ….

This blog briefly talks about how to override the default security related information associated with a JAX-RS request i.e. how to mess with the SecurityContext

Wait.. Security Context ?

  • Think of it as a JAX-RS abstraction over HTTPServletRequest for security related information only
  • Can be used for
    • figuring out how the caller was authenticated
    • extracting authenticated Principal info
    • role membership confirmation (programmatic authorization)
    • and whether or not the request was initiated securely (over HTTPS)

Ok, but why would I need a custom implementation ?

It helps when you have a custom authentication mechanism not implemented using standard Java EE security realm

  • your web container will not be aware of the authentication details
  • as a result, the SecurityContext instance will not contain the subject, role and other details (mentioned above)
  • a typical example is token based authentication based on custom (app specific) HTTP headers

Your RESTful application would definitely want to make use of the authenticated caller

  • the JAX-RS request pipeline needs to be aware of the associated ‘security context’
  • make use of it within its business logic

How to…

SecurityContext is an interface after all..

  • just implement it
  • inject it (using @Context) and use it in your resource methods



Posted in Java EE | Tagged , , , | Leave a comment

Asynchronous JAX-RS: basics & gotchas

This blog post covers

Man, I tend to blog a lot about JAX-RS and REST !

Basics of server side async JAX-RS

On the server side, asynchronous behaviour is driven by

  • @Suspended: annotation which instructs the container to inject an instance of AsyncResponse and invoke the method asynchronously
  • AsyncResponse: bridge between the application logic and the client request

Since we have clearly expressed our asynchronous requirements, the container will ensure that

  • the calling thread is released
  • the actual business logic is executed in a different thread (in this case its the thread pool taken care of the by the Managed Executor Service in the Java EE container – thanks to Concurrency Utilties in Java EE 7)

Things to watch out for .. a.k.a gotchas

Although the calling (request) thread is released, the underlying I/O thread still blocks until the processing in background thread continues.In the above example, the caller would have to wait 5 seconds since that’s the delay we have purposefully introduced within the code. In simple words, the client (e.g. browser executing a HTTP GET) keeps waiting  until the business logic execution is finished by calling the resume method of the injected AsynResponse object (remember, it’s the bridge b/w the application & the client).

Timeouts to the rescue

One can specify a time out period after which the client gets back a HTTP 503 Service Unavailable response (default convention)

Fine grained time outs

The default behaviour (HTTP 503 on time out) might not be suitable for all use cases. For example, you might want to implement a solution where a tracking identifier needs to be sent to the client (for future) if the actual processing does not finish in due time (before timeout triggers). Having the ability to send a custom HTTP response on time out can prove useful. The AsyncResponse API makes this possible via the notion of a time out handler. You can do this by

  • a direct HTTP response (see below example)
  • via an exception (by passing an instance of Throwable to AsyncResponse#resume)

Client side async using the JAX-RS Client API

Using asynchronous behaviour on the client side is pretty easy. All you need to do is obtain an instance of AsyncInvoker by calling async on the Invocation.Builder

Above gotchas applicable here

As you might have already observed, async behaviour in (server side) JAX-RS is not the same as in other typical async APIs i.e. the client is still blocked.

  • You should use the async method (as demonstrated above) to call a server side REST API in an async manner even if the server REST API itself is asynchronous in nature (implemented using @Suspended AsyncResponse) .

I repeat: do not be under the impression that just because the server API is async, your client thread will return immediately

  • The call to async returns an instance of Future object – and you might already know, the get method (of Future)  blocks. So use it with care and at the correct point in your application logic

Further reading

That’s all. Be async. Be safe



Posted in Java EE | Tagged , , , , | 1 Comment