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 , , , | Leave a comment

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 , , , , | Leave a comment

Efficient JAX-RS: Conditional GETs & PUTs

This post discusses how to leverage features in the JAX-RS API to execute RESTful operations based on conditions/criteria in order to aid with scalability and performance. It covers

  • which HTTP headers are involved
  • which JAX-RS APIs to use
  • details of the entire request-response flow

Required components

Must know HTTP headers

It would be awesome if you have a basic understanding of (at least some of) these HTTP headers (since these form an important part of the JAX-RS feature discussed in this post). These are best referred from the official HTTP specification document

  • Cache-Control
  • Expires
  • Last-Modified
  • If-Modified-Since
  • If-Unmodified-Since
  • ETag
  • If-None-Match



  • CacheControl: Again, just a simple class. Why not read one of my existing blog posts on this topic ?
  • EntityTag: JAX-RS equivalent (simple class) of the HTTP ETag header
  • Request: the main API which contains utility methods to evaluate the conditions which in turn determine the criteria for access

What are we trying to achieve ?

A simple interaction with a JAX-RS service can be as follows

  • Client sends a GET request
  • Server replies back with the requested resource (with a HTTP 200 status)
  • It also sends the Cache-Control & Last-Modified headers in response

Cache-Control defines the expiration semantics (along with other fine grained details) for the resource on the basis of which the client would want to

  • revalidate it’s cache i.e. invoke the GET operation for same resource (again)
  • make sure it does so in an efficient/scalable/economic manner i.e. not repeat the same process of exchanging data (resource info) if there are no changes to the information that has been requested

Common sense stuff right ?

Let’s look at how we can achieve this

Option 1

Leverage the Last-Modified and If-Modified-Since headers


  • Server sends the Cache-Control & Last-Modified headers as a response (for a GET request)
  • In an attempt to refresh/revalidate it’s cache, the client sends the value of the Last-Modified header in the If-Modified-Since header when requesting for the resource in a subsequent request
  • Request#evaluatePreconditions(Date) determines whether or not the value passed in the If-Modified-Since header is the same as the date passed to the method (ideally the modified date would need to extracted from somewhere and passed on this method)

(slightly) advanced usage

ETag header in action


  • In addition to the Last-Modified header, the server can also set the ETag header value to a string which uniquely identifies the resource and changes when it changes e.g. a hash/digest
  • client sends the value of the ETag header in the If-None-Match header when requesting for the resource in a subsequent request
  • and then its over to the Request#evaluatePreconditions(EntityTag)

Note: With the Request#evaluatePreconditions(Date,EntityTag) the client can use both last modified date as well as the ETag values for criteria determination. This would require the client to set the If-Modified-Since header

Making use of the API response…

In both the scenarios

  • if the Request#evaluatePreconditions method returns null, this means that the pre-conditions were met (the resource was modified since a specific time stamp and/or the entity tag representing the resource does not match the specific ETag header) and the latest version of the resource must be fetched and sent back to the client
  • otherwise, a HTTP 304 (Not Modified) response is automatically returned by the Request#evaluatePreconditions method, which can be returned as is

Please note …

  • Choice of ETag: this needs to be done carefully and depends on the dynamics of your application. What are the attributes of your resource whose changes are critical for your clients ? Those are the ones which you should use within your ETag implementation
  • Not a magic bullet: based on the precondition evaluation, you can help prevent unnecessary exchange of data b/w client and your REST service layer, but not between your JAX-RS service and the backend repository (e.g. a database). It’s important to understand this

Can I only improve my GETs …?

No ! the HTTP spec cares abut PUT operations as well; and so does the JAX-RS spec:-)


  • Server sends the Cache-Control & Last-Modified headers as a response (for a GET request)
  • In an attempt to send an updated value of the resource, the client sends the value of the Last-Modified header in the If-Unmodified-Since header
  • Request#evaluatePreconditions(Date) determines whether or not the value passed in the If-Unmodified-Since header is the same as the date passed to the method (in your implementation)

So the essence is..

  • If the API returns a non null response, this means that the pre-conditions were not met (HTTP 412) i.e. the resource was in fact modified after the time stamp sent in the If-Unmodified-Since header, which of course means that the caller has a (potentially) stale (outdated) version of the resource
  • Otherwise (for a null output from the API), its a hint for the client to go ahead and execute the update operation
  • In this scenario, what you end up saving is the cost of update operation executed against your database in case the client’s version of the resource is outdated

Further reading


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

JAX-RS, JWT & a pinch of JSR 375

This is another version of my previous blog on JAX-RS and JWT which includes a pinch of Java EE Security API (new JSR in Java EE 8). In case you are completely new to JSR 375, please jump to the last section of this blog and use the resources listed there

But, what’s new ?

Uses the following features powered by the draft JSR 375 implementation available here

  • HTTP Basic Authentication
  • an Embedded Identity Store

Changes made…

  • No need to define the actual realm, user and groups in the application server security configuration. The container realm used to act as the identity/credential store. This was replaced by implementation of an Embedded Identity Store by JSR 375. All that was required is the declaration of @EmbeddedIdentityStoreDefinition



Note: Java EE Security API also provides options for Database and LDAP as Identity Stores

  • POM changes: include the JSR 375 API and its RI

 More on JSR 375




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

JSON Web Token in action with JAX-RS

This post is about using JSON Web Token (JWT) with JAX-RS

It covers

  • Real quick intro to JWT
  • Shows how to use it with JAX-RS (for authentication) with an example


Brief intro to JWT

  • A standard defined by RFC 7519
  • Used to exchange claims
  • Has a pre-defined structure

Anatomy of a JWT

It consists of three parts

  • Header: consists of info like signature mechanism, token type etc.
  • Body (Claims): the meat of the payload
  • Signature: signature of the contents to protect against tampered/malicious JWTs

These three components come together to form the actual token


  • Useful for implementing Stateless authentication
  • Compact: less verbose compared to other counterparts like SAML)
  • Flexible: Although its backed by a standard, you are free to choose your signature, claim attributes etc.

Please note that…

  • JWT is not only an authentication mechanism. It’s more about information exchange & it’s usage is limited by your imagination
  • It’s signed, not encrypted: its contents can be picked up over the wire if you do not secure your transport layer (e.g. using HTTPS)

Using JWT with JAX-RS

Let’s look at an example of how we might use JWT in a JAX-RS based application. As stated earlier, this sample uses JWT as a stateless authentication token. The process is split into distinct steps

Getting hold of the JWT

Why do we need a JWT in the first place? It is because the JAX-RS resource is protected and its access is dependent on the presence of a JWT token within the HTTP request (this is achieved by a JAX-RS filter)

Think of JWT as a proxy to the actual username/password (or any other authentication criteria) for your application. You need to actually authenticate using the method required by your application in order to get access to the JWT. In this example, a successfully executed HTTP Basic authentication is the gateway to the token

This is what happens

  1. The application executes a GET request to the URL http://<host&gt;:<port>/<context-root>/auth/token with the HTTP Authorization header containing user credentials
  2. HTTP Basic authentication kicks in. This is enforced by the web.xml (snippet below) which ensures that any request to the /auth/* is not allowed to pass unauthenticated
  3. In case of a successful authentication, the JWT is returned in the HTTP response header

Here is an excerpt form the web.xml


Quick review of JWT creation code and its result


JWT in action

  • The JWT is sent by app in the subsequent request for the JAX-RS resource i.e.http:<host>:<port>/<context-root>/resources/books
  • The JAX-RS Container Request Filter kicks in – it checks for the presence of the JWT , verifies it. The verification process implicitly checks for presence of the required claim attributes as well as the signature validation

JWT verification snippet

  • It allows the request to go through in case of successful verification, otherwise, the filter returns a HTTP 401 Unauthorized response to the client
  • A container response filter ensures that the JWT is added as a part of the response header again. It only does so when the JWT verification was successful – this is made possible using the contextual state/information sharing feature provided by JAX-RS Request Filters

Other considerations

Choice of claim attributes

In this example, we just used the standard sub (subject) attribute in the claim. You are free to use others. I would highly recommend reading section 4 of the JWT RFC for deeper insight


JWT expiration

One should also consider expiring the JWT token after a finite time. You would need to

  • Make use of the exp claim attribute (standard)
  • Think about refreshing the JWT token (after expiry)

Revisiting the Stateless paradigm..

Although the initial authentication was executed using HTTP Basic, the application does not rely on a Session ID for authorising subsequent requests from the same user. This has the following implications

  • There is no need to store the session ID on the server side
  • There is no need to sync this session ID to multiple application nodes in a cluster

As stated above, JWT is helping us with Stateless authentication (it is not very different from the HTTP protocol itself)

  • Our JWT contains all the required data (claim) for the conversation (in this case authentication)
  • We pass the token with each HTTP request (only to access resources which are protected by the JWT to begin with)
  • The application does not need to repetitively authenticate the user (via the username-password combo)

Now we can scale:-)

You can have multiple instances (horizontally scaled across various nodes/clusters) of your JAX-RS service and yet you need not sync the state of the token between various nodes. If a subsequent request goes to different node than the previous request, the authentication will still happen (provided you pass the JWT token)

Using the sample project

If you want to play around with the example, please follow hese steps

  • Get the maven project and build it (same old maven clean install)
  • Deploy on a Java EE 7 container
  • Tweak your server security options to protect it using a realm named file and ensure that you include the members under the users group. Both these constraints are dictated by the web.xml descriptor (see above) – you can also choose to modify it as per your choice. Here is a snapshot from the Payara server


  • Issue a HTTP GET to http://localhost:8080/jax-rs-with-jwt/auth/token
  • Copy the token in the HTTP response header (jwt)


  • Issue a GET request to http://localhost:8080/jax-rs-with-jwt/resources/books and include the JWT in the HTTP Authorization header (prepend it with Bearer)



I am sure there are lots of other uses of JWT itself. Hopefully this gives a decent starting point to using them within your JAX-RS services


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