Screencast: Part 1 – JavaEE 7, Mongo, REST, Mobile

This is the first part of a 3 part blog/screencast on creating an end to end application that scrape data of a source and then re exposed these data as RESTful web services.

In the first part, we will look at pulling data into our web application.

In the second part, we will expose these data as RESTful web services

In the third and final part, we will write a mobile client to consume the web services.

The technologies that we will be using will be JavaEE 7 (tutorial), Mongo database and AngularJS/Ionic on the front end.

In this first part, we will be reading RSS feed from BBC Football site (the RSS feed is right at the bottom of the page). The feed entries are saved to Mongo. The following diagram illustrates this


The feed is read at regular interval. This feature is implemented using JavaEE 7’s ManagedScheduledExecutorService which is a thread pool managed by the application server.

JavaEE application servers supports the concept of connection pooling, in particular database connection pool. However this support only extends to RDBMS. So if you’re using NoSQL databases, then you’re out of luck. One solution is to implement custom resources like this particular example for Glassfish.

Luckily for us, MongoClient, the Mongo’s Java driver has an internal pool (and is thread-safe!). So we can create one instance of MongoClient and get this instance to dish out connection as and when its required. To using this instance as a singleton, we use CDI to wrap it in an ApplicationScoped object. This ApplicationScoped object ensures that only a single instance of MongoClient is created and used throughout the entire application.

The following screencast shows how we create the a JavaEE web application, read RSS feed from BBC Football website and save that into a Mongo database.

The source code can be found here.

Till next time.

Using OAuth For Your JavaEE Login

matrix_spoon_boy In my previous blog I  describe how we could add additional security layer to Java EE’s login process. The application server holds a  set of valid username/password; users are authenticated against this set of credentials.

Managing username/password is hard work; what if you are only interested about the user but not necessarily in maintaining the user. If your security requirement is not that stringent, then I could let somebody that I trust  validate that user. Once the user is validated, I can find out about the user. So you don’t maintain any username/password database. As far as you are concern there is no user.

Enter OAuth; it is a standard at allows an application to access data that a user holds in a 3rd party application. In order to access the data, the user first have to authenticated into that 3rd party application; once we pass the authentication stage, then we are authorized to access the data. The really nice thing about OAuth is that you never have to reveal your username or password to the application.

A use case might be an application would like a user’s valid email; one source of this might be from Google. So by using OAuth, the user can authorize Google to release this piece of information to the application. For more details on OAuth watch this video.

For the remainder of this blog, we will look at

  1. how to use Google’s OAuth2 provider for authentication and authorization; we’ll look at what are the information/resources we can release and how to go about doing that
  2. how to integrate/use Google’s OAuth2 as our authentication mechanism for a web application.

Register and Configure Your Application

To start using Google as our OAuth2 provider, you’ll need first do the following list of things

  1. Create a project or service account (in Google)
  2. Create a new client id
  3. Select the information/resources that your application wishes to use
  4. Optionally, configure the consent screen

Here is how everything hangs together:

  1. An user Fred, attempts to access some restricted resources/page on the JavaEE application. The JavaEE application server determines that Fred need to first login.
  2. The web application redirect Fred to  Google’s login page. Fred proceeds logins to his Google account; if Fred has already login to his account, then he will not need to relogin.
  3. After Fred has successfully login, Google OAuth2 provider will display the consent page. The consent page provides details about the web application and more importantly what resources is it trying to access, eg Fred’s email and Google+ id, his drive, etc.
  4. If Fred consents, Google now redirects the browser back to our web application

Now lets look at these steps in greater detail.

The first thing you’ll need to do is to create a project using Developer Console. This project is our JavaEE’s representation in Google’s universe. When a user gives permission to our JavaEE application to access his email, the user is actually giving permission to this project.


In the example above, my project’s name is Gatekeeper and the project id is gatekeeper-sg1. Go into the project by clicking on the project’s name. On the left hand side, expand ‘API & auth’ menu item and you should see APIs, Credentials and Consent Screen.

To create client id, click on Credentials, followed by clicking on CREATE NEW CLIENT ID.


Decide on the type of application you are developing. In our case its going to be a web application. Next you’ll have to configure 2 pieces of additional information associated with Web Application. The Authorized JavaScript is your application’s address in this case is the application’s domain. Since I’m writing a demo, that will be localhost with the port number. The Authorized redirect URI is the URI that Google will redirect to after the user has successfully login and have given permission for our application to access certain information.


The above shows the newly created client id. We will need the Client ID, Client secret and Redirect URIs later when we write our web application.

So the next thing we need to decide is what do we want to access from a user’s Google account. Click API under APIs & auth. You will now see a list of all the resources available. For our case, we are only interested in basic information, so we’re going to enable Google+ API. Enable all the API that the application will be needing. Note that most of these API have a daily limit (for free use). We’ll look at how to use the Google+ API that we have enabled in the next section

One final, you can customize the consent screen by entering the web application’s url, image, T&C, etc under the Consent screen menu.

Exploring the API

As I’ve mentioned earlier, Google provide lots of resource that we can access. In our case we are interested in a user’s Google+ details. All of these resources are access using REST. Google provides a playground for you to experiment with these API. The playground allows you to

  • Find out what are the resources available eg. under Google+ there are different resources like email, profile, login
  • How to invoke them
  • What is the structure of the returned JSON data
  • What are the OAuth2 scopes (more on scopes later) namespaces

s3 Assume we are going to get basic detail about a user from his Google+, so let see how we do this using playground.

Open up playground. Under Step 1, look for Google+ API v1 (don’t forget to enable it in your application). Under that you will see list of information accessible. Select the information that the application will need to access; what we are saying here is that if a user eg Fred logins to our web application, then Fred will have to provide these information to the web application. The consent page will display these details. So check whatever details you want to access. As a best practice, ask for the minimum amount of information in order for your application to establish a trust relationship with the user.

The URL that you see are the scopes. Make a note of these eg. if the example on the left, I have 3 scopes:, and

Once you’ve selected all the API, click on the Authorize APIs button. This is to authorize playground application (for testing) to access these resources from your Google account.

If you’re using this the first time, then you’ll probably see Playground’s consent screen requesting permission to access to API from Step 1 above. Click on Accept to proceed. If you don’t then you cannot test those APIs.

s4 Once you’ve consented, you’ll be taken to Step 2. Nothing much to do here except to click on Exchange authorization code button which will now take you to Step 3. We are now ready to test the Google+ API. Click on List possible operations button. Depending on what you’ve request in Step1, you will now be presented with a list of URL that you can call.


Select Userinfo (in our case) from the list then click on Send the request.


From the response, you can see the JSON structure of the resource. So by using the playground, you can find out

  1. What is the URI for a particular to get a particular piece of information
  2. What is the HTTP method to use
  3. What is the JSON structure of the result
  4. What are the required scopes (from step 1)

Integrating with JavaEE

We now have everything we need from the OAuth provider, we will now look at how to add this to our web application.

Start by configuring your web application to use form based authentication. You should provide a login page with a button to login via Google.

<form method=”GET” action=”googleplus”>
   <button type=”submit”>Login</button>

You could also provide the option of using the traditional way of login with j_security_check.

We will now have to write a servlet that maps to googleplus. This servlet will be performing the OAuth2 setup and login. Lets look at the code first

public class GooglePlusServlet extends HttpServlet {

   private static final String CLIENT_ID = "client id here";
   private static final String CLIENT_SECRET = "client secret here";

   protected void doGet(HttpServletRequest req, HttpServletResponse res)
      throws IOException, ServletException {

      ServiceBuilder builder= new ServiceBuilder();
      OAuthService service = builder.provider(Google2Api.class)
         .scope("openid profile email " +
               " " +
         .build(); //Now build the call

      HttpSession sess = req.getSession();
      sess.setAttribute("oauth2Service", service);


GooglePlusServlet is the servlet that will handle the OAuth login.Google has documented the authentication exchange here. I’m however going to using the excellent Scribe library. From the ServiceBuider we lookup Google’s OAuth2 Provider class. Once we have the OAuthService, we need to set the client id, the client secret and the URI callback . All these 3 pieces of information must match the project we created earlier.

Next comes the scope information; scope is use to indicate to Google what resources are we interested in accessing. In other words what is the scope of this request. The scope in this case must always start with the string openid followed by a space delimited scope namespaces. The 2 standard namespaces are profile and email. If we just have those 2 namespace, then we are saying that we are interested in the user’s profile and email. Google supports additional scopes for its services. This is where playground comes in. If you recall, when we were exploring the API, we are also shown the scope. If we want the request to access the user’s G+ profile and circles, then add their scope namespaces to the scope() method as shown above.

Note: Scribe supports may OAuth providers out of the box. However Google is NOT one of them; the reason is found here. This gist adds support for Google. Add the Google2Api class into your project and you’re good to go.

After constructing OAuthService, save that in the session cause we’ll be using it in the next phase of the authentication.

Now its time to forward our request to Google. Get the authorization URL from service.getAuthorizationUrl() and perform a redirect to it. So what is going to happen now is

  • If you are not login to your Google account, you will now be asked to do so.
  • If this is the first time you are using the web application, you will be shown the consent screen. You can now choose to accept or reject. Once you’ve consented to the request, this permission is saved into the user’s account permissions.

Google will now perform a callback to the configured callback URL. To handle the callback, we’re going to need another servlet

@WebServlet(urlPatterns={"/oauth2callback", asyncSupported=true)
public class OAuth2CallbackServlet extends HttpServlet { @Override
   protected void doGet(HttpServletRequest req, HttpServletResponse resp)
      throws IOException, ServletException {

      //Check if the user have rejected
      String error = req.getParameter("error");
      if ((null != error) && ("access_denied".equals(error.trim())) {
         HttpSession sess = req.getSession();

      //OK the user have consented so lets find out about the user
      AsyncContext ctx = req.startAsync();
      ctx.start(new GetUserInfo(req, resp, asyncCtx));

public class GetUserInfo implements Runnable {
   private HttpServletRequest req;
   private HttpServletResponse resp;
   private AsyncContext asyncCtx;
   public GetUserInfo(HttpServletRequest req, HttpServletResponse resp, AsyncContext asyncCtx) {
      this.req = req;
      this.resp = resp;
      this.asyncCtx = asyncCtx;

   public void run() { 
      HttpSession sess = req.getSession();
      OAuthService serivce = (OAuthService)sess.getAttribute("oauth2Service");

      //Get the all important authorization code
      String code = req.getParameter("code");
      //Construct the access token
      Token token = service.getAccessToken(null, new Verifier(code));
      //Save the token for the duration of the session
      sess.setAttribute("token", token);

      //Perform a proxy login
      try {
         req.login("fred", "fredfred");
      } catch (ServletException e) {
         //Handle error - should not happen

      //Now do something with it - get the user's G+ profile
      OAuthRequest oReq = new OAuthRequest(Verb.GET,

      service.signRequest(token, oReq);
      Response oResp = oReq.send();

      //Read the result
      JsonReader reader = Json.createReader(new ByteArrayInputStream(
      JsonObject profile = reader.readObject();
      //Save the user details somewhere or associate it with
      sess.setAttribute("name", profile.getString("name"));
      sess.setAttribute("email", profile.getString("email"));

The callback is routed to this servlet; we check if the user have rejected the request. If not we proceed to get the user’s details. I’m using an async servlet here because we’ll be making request out to Google for the user’s info and we do not want to hold on to the request processing thread.

If the user have consented to the request, then get the code from the query string. This is the most important parameter. Using the code we construct the access token. For every request to Google, we will need the access token to use the token to sign it. Constructing a new token is quite straight forward. You can also refresh an old token by passing in the token as the first parameter in getAccessToken(). Once you have gotten your token, save it in the session.

We are now ready to get the user’s profile. For your experimentations in the playground (step3), you now know which URL to use and what HTTP method to use. Construct that using OAuthRequest class. Sign it with the token, before making the call.

When the response, returns parse it using a Json parser. Since I’m using EE7, I’ll be using the Json API to perform this. Again, from playground, we know the structure of the Json response from Google. You can now save all the relevant information.

One last thing before we end. So we have successfully authenticated with Google using OAuth. But we have not login to the application. To do that, I’ve decided to create a proxy user in the authentication realm of the application server. After you have authenticated with Google, login to this proxy user so that the application server will honour all the security declarations. Just be aware that you cannot use getRemoteUser() or use getPrincipal() to get a user’s detail. A more tightly integrated approach would be to develop a custom realm (Glassfish in this example). However custom realms may not be portable.

One More Time…

There are may details and configurations so before I end lets go through the steps again

  1. Setup Project
    1. Create a project in Google (from Developer Console)
    2. From the project, create a new client id (note the client id, client secret and redirect url
    3. Enable the API that the project is going to access
  2. Find out abut the API 
    1. Go to playground
    2. Select the same API that you have enabled
    3. Note their scope, http method, URL and the response
  3. Integrate with WebApp
    1. Configure for based login
    2. Write a servlet to construct an OAuth request.
    3. Write a servlet to handle to callback
  4. Till next time…

Using JSONP with JAX-RS

JSONP is a format used to work around the same origin policy. As the name implies it is a modification on the JSON format. Instead of returning a JSON object like so

{ "customerId": 123, "name": "fred", "email": "" }

the JSON is return as a method call to a function like so

foo({ "customerId": 123, "name": "fred", "email": "" })

JSONP is typically used in cross origin AJAX calls using the GET method. You can learn more about JSONP from this Stack Overflow discussion. The JSON-P website talks about why and when it is used.

Handling JSONP

We will examine JSONP by first looking at how we use it from the ever popular jQuery. To make an cross origin AJAX call with JSONP we use $.ajax() like so

   type: "GET",
   url: "webresources/customer/1",
   dataType: 'jsonp' })
.done(function(result) {
   //Do something with the result
   console.log("----> " + JSON.stringify(result));
}).fail(function() {
   //Handle failure

Lets assume that our AJAX call is going to get a customer record. The HTTP request goes across to the server

GET /JSONPTest/webresources/customer/1?callback=jQuery210012143543711863458_1393227259817 HTTP/1.1
Accept: text/javascript, application/javascript, application/ecmascript, application/x-ecmascript, */*; q=0.01

and the response

HTTP/1.1 200 OK
Content-Type: application/javascript

Notice that the callback function name is in the query string of the request.

So to write a JAX-RS resource to handle we need to

  • Handle the HTTP GET method
  • Read the callback parameter in the query string. We will use the name of the function to wrap our result
  • Produce the MIME type in the Accept header

The following JAX-RS resource should handle the JSONP request

public class CustomerResource {

   @PersistenceContext EntityManager em;

   public String get(@PathParam("id") Integer id ,
         @QueryParam("callback") String callback) {

      Customer cust = em.find(Customer.class, id); 
      if (null == cust)
         throw WebApplicationException(Response.Status.NOT_FOUND);

      //Convert object to JSON
      JsonObjectBuilder builder = Json.createObjectBuilder();
      return (callback + "(" + + ")");

The code is quite straightforward. We inject the callback query string into the handler which we subsequently use to wrap the result.

As you can see, its quite simple to handle JSONP.

JSONP as MessageBodyWriter

JAX-RS has a pair of SPI call MessageBodyReader and MessageBodyWriter that allows anyone to handle marshalling and unmarshalling of objects from HTTP to JAX-RS resources. I wrote a simple MessageBodyWriter , called JSONP4JAXRS, that simplifies the entire process (if you don’t mind adding 12K to to your project).

If you’re using JSONP4JAXRS, then the above CustomerResource can rewritten as follows

public class CustomerResource {

   @PersistenceContext EntityManager em;

      public String get(@PathParam("id") Integer id ) {

      Customer cust = em.find(Customer.class, id); 
      if (null == cust)
         throw WebApplicationException(Response.Status.NOT_FOUND);

      //Convert object to JSON
      JsonObjectBuilder builder = Json.createObjectBuilder();
      return (; 

No more fiddling around with callback parameter. The MessageBodyWriter will automatically pad the JsonObject with the callback.

But wait! There is more!

JSONP4JAXRS will automatically pad any return types according to the following rules:

Return Type Padding (assume fn is the name of the callback function)
JsonObject fn({ … }) where { … } is the JsonObject
JsonArray fn([ … ]) where [ … ] is the JsonArray
Any primitives including their  wrappers fn({“value”: the_value })
Any object fn({“value”: toString_value_of_object})
Iterable  fn([ … ]) The Iterable is converted to a JsonArray and the elements are converted according the the above rule

Don’t forget to wrap your Iterable (eg. List<JsonObject>) in a GenericEntity if you are returning the result via a Response.

The JSONP4JAXRS contains a class call JsonWithPadding that defines the following constants for JSONP MIME types

Constant Name MIME Type
APPLICATION_JAVASCRIPT application/javascript
APPLICATION_JSON application/json
APPLICATION_ECMASCRIPT application/ecmascript
APPLICATION_X_ECMASCRIPT application/x-ecmascript
TEXT_JAVASCRIPT text/javascript

JSONP4JAXRS works with Java EE 7 only. JSONP4JAXRS can be downloaded here. The source and binaries are in the compile NetBeans project file. The binaries is in dist directory.

Till next time.

Integrating TOTP with Java EE’s Container Managed Security

clip_image002Edited on Monday Febuary 1 2014

After reading the following blog on time-based one time password (TOTP), I wanted to see if I could add an additional layer of security into Java EE’s  security. I installed Google Authenticator on my phone and started experimenting it with Java EE security.

I’ll describe what I did and some of the issues I found. You can get a copy of the source when you reach the end of the blog. Hopefully the journey is as pleasant as the destination 😉

The blog is broken into the following sections

  1. In the first part, I’ll give a brief intro to Google Authenticator/time based onetime password and how it works
  2. Setup JDBC realm for Glassfish application server in preparation for using it in our form based authentication
  3. Create the login and user registration with JSF Faces Flow
  4. Configure container managed security to use TOTP for login

Time-base One Time Password

So lets start with TOTP. We are all familiar with the concept of password. Password are typically static; they do not change over time; so if someone knows your password then your account is compromised.

In most operating system you can configured a password expiry policy where users are forced to change their password at regular intervals eg. 6 months. This password expiry policy gets around the above mention problem every 6 months. But the risk still exist.

TOPT takes the password expiry policy to the extreme by expiring your password at an even faster rate like say every 30 seconds! The problem here is that you cannot change your password every 30 seconds; so to make this work, TOTP uses an algorithm to change the password for us.

Very briefly this is how the TOTP works: you pass to the TOTP password generator algorithm a secret key and the current time; out pops your password; So if you call the TOTP password generator now and then again 30 seconds later (assuming that your window is 30 seconds) using the same secret key, you will get 2 completely different passwords.

To verify a password generated by TOTP algorithm, the TOTP password verification must know your secret key and the time that the TOTP password is generated. Since its a 30 second expiry period in our example, the password verifier will be able to validate the password as long as it is run inside the same 30 second window when the password is generated. All the wonderful math can be found here. TOTP is an IETF standard RFC6238.

Examples of TOTP can be found in online banking like DBS’s OTP where the account holders are issued dongles that implement the TOTP algorithm along with their unique secret keys embedded in the dongles. 

Another way of using TOTP is to augment it with your regular password as in Google’s 2-Step Verification (the focus of this blog). Google’s 2-Step Verification (G2SV) relies Google Authenticator which replaces the dongle in the above example. You have to first create an account. The Authenticator captures your TOTP details of this account by scanning a QR code. The QR code is created from the following 3 pieces of information

  1. A base 32 encoding of a 10 digit hexadecimal number. Eg the bytes from the string 8-polytope (“8-polytope”.getBytes()) will produce the following base 13 encoding: HAWXA33MPF2G64DF. This is the secret key and is unique to each user
  2. An issuer, typically the name of a company or the issuing authority eg. Yoyodyne Propulsion Systems
  3. A label, which I like to call the subject, is the user’s name or some identifier eg. johnwhorfin

All the information have to be encoded in the otpauth format. If we were to encode the values from above, we will get the following


Note that the otpauth string have to be URL safe. We can how use this otpauth to generate a QR using Google’s QR generator. You can find the query string parameters here. So to get the QR code of 350×350 pixel in size, enter the following

See the QR in its full glory here.  Of course the entire process of generating the OTP can be automated.

Clearly the secret key in which the entire TOTP scheme hinges is the weakest link. If we minimize the exposure of the secret key (like keeping it from the user, using HTTPS to generate the QR) then we can potentially make using TOPT reasonably secure. Well get to that a little later.


Glassfish JDBC Realm

Java EE security realms is a place where username, password and groups are stored. When you configure security for your application you need to specify which security realm you application will be associated with. When a user login to your application, it is from this realm that the application will get the user’s credentials, password and group id. See here for more details.

A JDBC realm is a realm where usernames, passwords, etc are stored in a RDBMS. You first create the required tables in a RDBMS; next you create a connection pool on top of it followed by a JDBC resource.

Since I’m using Glassfish and Java DB/Apache Derby, I’ll be creating and configuring JDBC realm based on these. There are lots of blogs and tutorial on creating JDBC realm for Glassfish so I won’t go into it in great detail. I’ll just list out my configuration.

The following are the table schemas, based on Apache Derby, which I’ve copied from this blog. Adapt it to whatever database you’re using.

create table logintable (
   username varchar(128) NOT NULL CONSTRAINT usernamePK primary key,
   password varchar(128) NOT NULL,
   otp_secret varchar(128) NOT NULL

create table grouptable (
   username varchar(128) NOT NULL,
   groupid varchar(128) NOT NULL,
   CONSTRAINT GROUP_PK PRIMARY KEY(username, groupid),
   CONSTRAINT USER_FK FOREIGN KEY(username) REFERENCES logintable(username)

I’ve added an extra column in logintable called otp_secret. This column will be used to store our OTP secret key.

Create a JDBC resource to the database that has the above 2 tables; see here if you do not know how. Assume that the JDBC resource name is jdbc/security. Next define a JDBC realm for Glassfish with the following configuration according to the table schemas

Property Name Property Value
JAAS Context jdbc-realm (note: this is the realm’s name)
JNDI jdbc/security
User Table logintable
User Name Column username
Password Column password
Group Table grouptable
Group Table User Name Column username (note: this is the username column in grouptable)
Group Name Column groupid
Password Encryption Algorithm none (note: enter this value)
Digest Algorithm SHA-256 (note: this is important as you’ll need to know what message digest to use)

Login Flow for TOTP

The next thing that we’re going to do is to define a flow for a user to login or to register themselves. Registration is important here because this is where we generate the TOTP secret key. The following diagram shows the authentication and registration process


  • totp-login – this is the login page and the main entry point into this flow. The page need to have the same name as the flow name to indicate that this is the starting page
  • register – if we are a new user, then we click on a button on totp-login to get us here
  • qrcode – after we have successfully registered, the qrcode page will display the QR code for our TOTP which we have to use Google Authenticator to scan. After scanning, we return to totp-login to login
  • error – the error page

totp_flowI’ll be implementing the process using JSF using the new Faces Flows; so the files are created in a directory called totp-login; this incidentally will also be the name of the flow. 

Let start with the registration (register.xhtm) page. Note all JSF pages are at its bare minimum.

<h:form id="form">
   <h:inputText id="username" value="#{newUser.username}"/>
   <h:inputSecret id="password0" value="#{newUser.password}"/>
   <h:inputSecret id="password1" value="#{newUser.passwordAgain}"/>
   <h:commandButton value="Register Me" action="#{newUser.register()}"/>

And this is the backing bean for register.xhtml

public class NewUser {
   @EJB private UserManager mgr; 
   //JavaBean properties - not shown
   public String register() {
      Map<String, String> result = OneTimePassword.generateQR(username, Authentication.ISSUER);
      mgr.register(username, password, result.get(OneTimePassword.SECRET32));
      qrUrl = result.get(OneTimePassword.OTPAUTH);
      return ("qrcode");

The code is quite simple. When the user clicks on Register Me button, we will call register(). After verify the fields, us use an EJB call UserManager to insert the username, password and the base32 encoded secret key into the JDBC realm. This corresponds to logintable above. It also assigns the user to a group called registered.

Recall that in our JDBC realm configuration, we say that we are using SHA-256 for the password digest; so in effect we don’t save the password but its digest. This hashing operation is performed by the register() method.

Before we register the new user into our database, we have to generate a secret key for it. We use generateQR(); generateQR() takes in 2 parameters, the subject and the issuer. In the example above, for the subject we will be using the user’s login name and the issuer is hardcoded to “Yoyodyne Propulsion Systems”. generateQR() returns a Map which hold a few entries. The name of the keys holds the following values

Key Name Value Description
secret32 Base32 encoded String of a randomly generated 10 byte secret
otpauth otpauth URI
url Full URL, with the otpauth, to the Google site that generates the QR code
secret Stringify 10 byte secret. Note in the demo, we only use the first 2 keys viz. secret32 and otpauth

We assign the otpauth URI to a property and move to the qrcode.xhtml page to display the QR code shown below

<h:outputText value="
   Please scan the QR code on the right using 
   your Google Authenticator App. After that you can 
   proceed to login."/>           
<h:commandButton value="Login" action="totp-login"/>
<h:graphicImage url="#{newUser.qrUrl}"/>     

A digression: I found that graphicImage cannot load images from an external source viz. if I pass it… I’ll get a broken image. Not sure if this is a bug with JSF (Majorra) or its part of the specs. Anyways, this blog pointed out a possible workaround by proxying the image via a Servlet. The otpauth is appended to /qrcode. So the url attribute in graphicImage references /qrcode/the_otpauth instead of… A Servlet is mapped to /qrcode/* to handle the image loading. See QRCodeServlet for more details.

All that remains now is the login page which is shown below

   <h:inputText id="username" value="#{authentication.username}"/>
   <h:inputSecret id="password" value="#{authentication.password}"/>
    <h:inputText id="otp" value="#{authentication.otpCode}"/>
   <h:commandButton value="New User" action="register"/>
   <h:commandButton value="Login" action="#{authentication.login()}"/>

and its corresponding backing bean

public class Authentication implements Serializable {
   //Getters and Setters not shown
   @EJB private UserManager mgr;
   public String login() {
      FacesContext ctx = FacesContext.getCurrentInstance();
      HttpServletRequest req = (HttpServletRequest)ctx.getExternalContext().getRequest();
      if (null != req.getRemoteUser())
         return ("protected/menu");
      if (null == req.getAuthType()) {
         ctx.addMessage(null, new FacesMessage("Not configured for container managed login"));
         return ("error");
      try {
         req.login(username, password);
      } catch (ServletException ex) {
         ctx.addMessage(null, new FacesMessage("Incorrect login"));
         return ("error");
      User user = mgr.getUser(username);
      if (null == user) {
         ctx.addMessage(null, new FacesMessage("Cannot find user."));
         return ("error");
      try {
         if (!OneTimePassword.checkCode(user.getOtpSecret(), otpCode, System.currentTimeMillis())) {
            ctx.addMessage(null, new FacesMessage("Incorrect login"));
            return ("error");
      } catch (InvalidKeyException | NoSuchAlgorithmException | NumberFormatException ex) {
         ctx.addMessage(null, new FacesMessage("Exception: " + ex.getMessage()));
         return ("error");
      return ("success");

The login() method takes a user name and password and will throw a ServletException if the that combination is incorrect. It will also throw ServletException under 2 other circumstances

  • If the application have not been configured for security. We check that using getAuth() method or
  • If we attempt to login a use that have been authenticated. So we check if we have the user name by calling getRemoteUser(). If this is not null, meaning that this request has been authenticated, then we redirect the request into the secure area. More on secure area later.

After successfully login, we perform the 2nd validation by checking the OTP. We pass in the secret key, which is returned when we get the User from getUser(), the OTP password that the user entered and the current time to OneTimePassword.checkCode(). checkCode() method is  this algorithm that I found here. checkCode() verifies the password using a 120 second window viz. if you give it the current time, it’ll take the current, past and future 30 second slot. If we don’t do that then the time on the OTP generator (the mobile phone that runs Google Authenticator) and the time on the server that host the web application cannot be more than 30 seconds apart.

Note that if the TOTP password is incorrect we perform a logout (logout()) before returning; the other method that you can use is HttpSession.invalidate() which performs a logout as well. The difference is that logout() will not destroy the HttpSession. One reason you might not want to invalidate the session is to keep a count of failed attempts and disable the username for 5 minutes for example.

If the OTP is correct, we exit the TOTP authentication flow by returning the success token. I’m using explicit flow definition, so the definition is as follows

<flow-definition id="totp-login">
    <flow-return id="success">

where everything under the /protected  directory requires authentication and authorization before access.


Form Based Authentication with TOTP

We’ll not turn our attention to configuring the web application with the totp-login flow described above using the JDBC realm that we have created. So if you want to secure an application in Java EE, you have to specify 3 things

  1. Authentication scheme – how are we going to collect username and password and to perform the authenticatoin
  2. Authorized role(s) – what are the application defined security roles
  3. Security constraint – what are the resources that needs to be authenticated and who is authorized to access it. The constraint ties authentication and authorization into a neat little package

Authentication Scheme

Let start the discussion by looking at authentication scheme. Java EE supports container managed security. If we’re dealing with securing web application, then common ways to authenticate a user are either basic or form-based (see here for other ways).

When you use basic authentication, you get a dialog box to request for your user name and password. If a correct combination of username and password is presented, then you will be redirected to the protected resource. Basic authentication does not give you control over the login page and the authentication process. Say you want to enter a third field, eg our TOTP field, as part of the the login, there is just no way of doing this.

Enter form based authentication. With form based authentication, you create a login and an error page in the web.xml file. The login page needs to contain j_username and j_password field; these values are POSTed to j_security_check. Form based authentication gives you control over the L&F of your login page but you’re still out of  the loop when it comes to the authentication process. Again it does not allow us to arbitrarily include any additional data into the authentication process. You can do it after you’ve passed security check but not during. Another common gripe with form based authentication is that its not very JSF friendly; you have to fallback to <form> and <input>.

So in Java EE 6, the Servlet API introduced programmatic security. At its heart, it is still form based authentication. However instead of relying of j_security_check to collect username and password, your application is now be responsible for collecting these information and performing the authentication. This opens up a lot of possibilities; you are no longer restricted to just username and password. You can include additional fields; see Authentication.login() and totp-login page above.

The following XML fragment shows form based authentication for our TOTP authentication


Note that in a typical form based login, you have 2 different views for login and for error. The container will redirect the request to the error page if you’ve login incorrectly. In our “semi” container managed security, our application controls this (see the flow above). So you don’t actually need an error page; I therefore set it to index.xhtml.

Another issue is cannot enter a JSF flow with a HTTP GET. In a typical form based login configuration, you provide the actual login page. In this scenario, we cannot have /faces/totp-login; this will not start the flow. What you need to do here is provide a view which have a POST back to start the totp-login flow; in this case index.xhtml looks like this

   <h:commandLink action="totp-login" value="Login"/>

Authorized Roles

Once you’ve setup the authentication mechanism, you now need to define a security role. Our demo application have a single role which is authenticated.


The authenticated role needs to be mapped to users and groups from the jdbc-realm. This mapping is application server specific. Glassfish uses a file called glassfish-web.xml to perform this mapping. The following XML fragment shows how we map authenticated to registered group.


Security Constraints

A security constraint defines what resources are to be protected and what roles are allowed to authorized to access it. Lets say we wish to secure everything under the /protected path. So when we try to access /faces/protected/menu, the application server will require you to be authenticated first; then check if you are authorized with the role to access that resource. In our case our security constraints looks like this


The above constraint says that what we are protecting is everything under the /faces/protected path; only those uses who are authenticated to the authenticated role will be authorized to access it.



The following are some screenshots with a running commentary of what’s happening


This is the login page. Assume that we are a new user, so we click on New User button. This brings us to the following screen


We enter the new user details. Then click on Register Me button. This will call NewUser.register(). A secret key will be generated and the appropriate QR code link is created based on the username, issuer and the secret key. The following page is displaying asking the user johnbigboote to scan that into his Google Authenticator.


After scanning in you should see the following in the Google Authenticator


The number 732803 is the OTP and the ‘pie chart’ to the right is the 30 seconds count down timer. After login you’ll be redirected to the secure area.


You can use this approach to integrate other authentication mechanism like adding CAPTCHA.

I’ve listed a few caveats in the blog. They are mostly related to JSF and not security. So let me just state one here. One of the big advantage of container managed security is that if you are going to access /faces/protected/menu resource and your are not authentication, the application server will redirect you to the login page (if we’re using form based authentication). After you have authenticated and you’re authorized to access that resource, the container will now redirect you to that resources which is /faces/protected/menu in our case.

But using programmatic authentication, you lose this ability. I have to go to a specific view after a successful login. I cannot find a way of redirecting the request back to the original resource. Let me know if you have a standard and portable way of doing this.

The source code can be found here. It’s been an extremely long blog. Didn’t start off that way. Thanks for reading.

Till next time.

Marrying Socket.IO Client with Java EE 7’s WebSocket

just_marriedSocket.IO is a JavaScript library that uses a variety of transport (WebSocket, XHR polling, etc) to allow you to develop real-time web application. Socket.IO hides the underlying transport mechanism by figuring out what is the best transport to use between the browser and the server. It performs a handshake to determine this. Most Socket.IO servers are written in JavaScript running in node.js.

Java EE 7 was released recently. One of the key themes of EE 7 is better support for HTML 5 application. The support for modern web application started in Java EE 6 with the inclusion of RESTful web services. In EE 7, the powers that be added WebSocket and JSON.

I was recently learning and mucking around with Socket.IO. A thought struck me; can I connect a Socket.IO client to a Java EE server? I did a little investigation; I found 2 server side Java implementation of Socket.IO. They are netty-socketio and Socket.IO-Java. While both are excellent implementations and have been used in production, they are tied to specific servers. netty-socketio is based on Red Hat’s async IO framework called Netty and Socket.IO-Java runs on top of Jetty leveraging its WebSocket and continuation support.

I wanted something cross platform using standard API and  more importantly, for me at least, to use Java EE’s programming model (what I’m familiar with) and utilize its resources (JPA, EJB, etc).

The following is a sort of step by step guide on how you integrate a Socket.IO client to Java EE 7 using the new WebSocket API (JSR-356). What I’m doing here is based on looking at Socket.IO-Java sources.

Something Old

When a Socket.IO client connects, it does 2 things

  • Sends a HTTP GET to /socketio to download the JavaScript file. This is the result of <script>
  • Sends a second HTTP GET to /socketio/1/ for the handshake. The server should respond with a colon delimited string comprising of the session id, heart beat timeout, default timeout and a list of supported transport separated by comma. Eg 123456:15000:10000:websocket,xhr-polling

The easiest way to handle the handshake part is to use Servlet and that has to be mapped to /*. Override doGet() and doPost() to handle the client request.

//Bare minimum, no error checking


public class SocketIOServlet extends HttpServlet {

   private static final String CONFIG = “:15000:10000:websocket”;


   protected void doGet(HttpServletRequest req, HttpServletResponse resp)

         throws IOException, ServletException {

      serve(req, resp);



   protected void doPost(HttpServletRequest req, HttpServletResponse resp)

         throws IOException, ServletException {

      serve(req, resp);


   private void serve(HttpServletRequest req, HttpServletResponse resp)

         throws IOException, ServletException {

      String path = req.getPathInfo().trim();

      path = path.startsWith(“/”)? path.substring(1): path;

      String[] paths = path.split(“/”);

      //GET / – returns the library

      if (“GET”.equals(req.getMethod()) && “”.equals(path[0])) {


         //Copy back to client, then return, not shown


      } else if (parts.length <= 2) {

         //Return handshake

         try (PrintWriter pw = resp.getWriter()) {

            pw.print(req.getSession().getId() + CONFIG);





The important thing to note is that in the handshake back to the client, we indicated that we only support WebSocket. See CONFIG constant.

Something New

Once the handshake is successful, the client will now attempt to communicate with us using WebSocket. WebSocket is the newest API in the EE 7 stack. Its very similar, in terms of programming style, to JAX-RS. See here for a comprehensive WebSocket tutorial.

To communicate with the client (Socket.IO), the WebSocket end point must be mapped to / eg / The session id is the variable part of the path so we need to create an endpoint with path parameter to match that but we will not be using it unless you are interested in specific clients.


public class SocketIOWebSocketHandler {


   public void open(Session session) {




   public void close(Session session) {





   public void message(Session session, String msg) {




So if you look at handling WebSocket transport with the client, its actually quite straightforward. The part that is might be a little confusing is why sendObject()? And what is in connect() and close(). Another question might be the format of msg.


Something Borrowed

Socket.IO defines a frame/packet based wire protocol that it uses for all communications between the 2 ends. A typical frame looks something like this

   3:::hello world

So if we were to receive some data from the client and print that out, we will see something similar to above.

As I’ve mentioned at the start of this blog, the code here is largely based on studying Socket.IO-Java sources. Instead of writing my own parser for the Socket.IO frames, I’m going to just use Socket.IO-Java’s. The class in question is SocketIOFrame. Its quite easy to use.

To parse a message from the client

List<SocketIOFrame> frames = SocketIOFrame.parse(msg);

SocketIOFrame has the following methods to identify the frame

  • getFrameType() – whether its a data frame or control frames
  • getMessageType() – text or JSON message
  • getData() – the data

So message() method above can be written as follows (we’ll only be covering the message)


public void message(Session session, String msg) {

   for (SocketIOFrame f: SocketIOFrame.parse(msg))

      switch (f.getFrameType()) {


         case EVENT:

         case JSON_MESSAGE:

         case MESSAGE:



Lets look at how a Socket.IO client sends each of these message type and how we handle it on the server. Assume that socket is a Javascript Socket.IO socket.


socket.send(“hello world”);





socket.json.send({message: “hello world”})



   StringReader data = new StringReader(f.getData());

   JsonReader reader = Json.createReader(data);

   JsonObject jsonData = reader.readObject();



socket.emit(“greetings”, {message: “hello world”});


case EVENT:

   StringReader data = new StringReader(f.getData());

   JsonReader reader = Json.createReader(data);

   JsonObject jsonData = reader.readObject();

   String eventName = jsonData.getString(“name”); // greetings

   JsonArray payload = jsonData.getJsonArray(“args”); // { … }

When you are sending data back to the client, the message have to be framed as well. Assume we have the following message handlers on the client

socket.on(“message”, function(data) {

   console.log(“MESSAGE: “ + data);


socket.on(“greetings”, function(data) {

   console.log(“greetings: “ + data);


The following shows how to send message to each of the above handlers

Sending as text

SocketIOFrame f = new SocketIOFrame(


      , SocketIOFrame.TEXT_MESSAGE_TYPE, message);


Sending as JSON

StringWriter w = new StringWriter();

try (JsonWriter writer = Json.createWriter()) {



SocketIOFrame f = new SocketIOFrame(


      , SocketIOFrame.JSON_MESSAGE_TYPE, w.toString());


Sending as custom event

JsonArray array = Json.createArrayBuilder()

      .add(/* add data as JsonObject to array */).build();

JsonObject json = Json.createObjectBuilder()

      .add(“name”, “greetings”)

      .add(“args”, array).build();

StringWriter w = new StringWriter();

try (JsonWriter writer = Json.createWriter()) {



SocketIOFrame f = new SocketIOFrame(


      , SocketIOFrame.JSON_MESSAGE_TYPE, w.toString());


A connect SocketIO frame (connect() method) is created like so

new SocketIOFrame(FrameType.CONNECT

      , SocketIOFrame.TEXT_MESSAGE_TYPE, “”)

and close SocketIO frame (close() method) is

new SocketIOFrame(FrameType.CLOSE

      , SocketIOFrame.TEXT_MESSAGE_TYPE, “server”)

Something Blue

The Socket.IO client makes the following assumption when communicating with the server

  • All communication endpoint are at viz. when you do io.connect(“http://myserver:8080”), it automatically look for the server side end point to be at http://myserver:8080/
  • All data send between the client and the server are enclosed in a frame defined by Socket.IO library
  • Following from the first point, the client always talks to the same end point. In the above example, all data are directed to http://myserver:8080/ So the handler must look at the data and dispatch to appropriate handlers. It would be nice if Socket.IO can use end points to discriminate the message handlers eg.  http://myserver:8080/

Lets address each of the above issues. When you deploy a Java EE web application, you always deploy it under an application context. Lets say the web application uses jsocketio as the application context, then you can use the resource option to remap the endpoint.

By default if you do the following

var socket = io.connect(“http://localhost:8080”); will look for the end point at http://localhost:8080/ as discussed above. To include the web application context, use the resource option

var socket = io.connect(“http://localhost:8080”

      { resource: “jsocketio/”});

See here for a detailed description of other options.

The workaround for SocketIO frames can handle using WebSocket’s encoders and decoders.

An incoming message first be passed to a decoder which converts the messages into a List<SocketIOFrame>. We then inject this list into the @OnMessage method. Note that in the above example we perform the decoding ourself. We can actually delegate this to decoders.

For outgoing messages, we have to create SocketIOFrame. Then use sendObject() to send it back to the client. The SocketIOFrame encoder will intercept this object and convert it to a frame.

public class SocketIOFrameDecoder

      implements Decoder.Text<List<SocketIOFrame>> {


   public List<SocketIOFrame> decode(String value)

         throws DecodeException {

      return (SocketIOFrame.parse(value));



   public boolean willDecode(String value) { return (true); }



public class SocketIOFrameEncoder

      implements Encoder.Text<SocketIOFrame> {


   public String encode(SocketIOFrame frame)

         throws EncodeException {

      return (frame.encode());




We now need to associate the encoder/decoder pair with SocketIOWebSocketHandler


      , encoders = { SocketIOFrameEncoder.class}

      , decoders = {SocketIOFrameDecoder.class}


public class SocketIOWebSocketHandler {


   public void message(Session session, List<SocketIOFrame> frames) {

      //Process inbound messages

      for (SocketIOFrame f: frames)

         //Do something


      //Send reply back

      SocketIOFrame sioFrame = new SocketIOFrame(…);



You can find more details on encoders and decoders here.

The third and final caveat when working with a Socket.IO client is that all messages are directed at the same endpoint URL. If you look at how Socket.IO is used with node.js, you’ll notice that you can attach handlers to events. I’ve talked about this above so I won’t be repeating myself here. It would be nice to be able to map event names, in particular those send by using emit(), to WebSocket handlers.


I’m currently working on a simple framework so I’ll post the complete code when I complete the framework.

Everything that I’ve described I’ve tested with Chrome, Glassfish 4 and NetBeans 7.4 beta. For some strange reason, Socket.IO client on refuses to use WebSocket on Firefox.

Till next time.

Implementing a Multi-Player XMPP Game – Part 2

In my previous blog, I looked at implementing a multi-player set game. Barring any bugs, the engine is working fine. We now turn our attention to writing the client and I’m faced with the following 2 questions:

Firstly what are we going to use to develop the client? What technology, language and platform are we going to implement this in?

Second question: once we’ve written the client, how are we going to get people to install and use it.

The answer I think is quite obvious: the web. By the web, we mean HTML(5), JavaScript and the browser.  So if this is the current thinking, is there a way that we can apply that here?

As you know, Vorpal applications are naturally web in the sense that they are masquerading as web application in a WAR file deployed into a web container. So far we have not really exploited this schizophrenic nature of Vorpal. I have flirted with it in a previous blog on Server Sent Events. It occurred to me that I could I could write the client for the Set game as a web application and deploy it along with server/engine component just like a regular web application.

The next question is how do you write do you write a HTML application that does XMPP? There are lots of JavaScript libraries that does this really well eg. Strophe.js. While these are excellent techniques for developing XMPP application on the web, they strike me as something of an add-on viz. running XMPP inside a browser whose primary conversation of choice is HTTP.

What I was thinking of was is there a XMPP client that has a browser component where the primary protocol is XMPP.  I could not find what I wanted so I wrote a prototype using JavaFX’s WebView. Here’s how it would work:


A user would login to a XMPP server using this XMPP client (shown above on the left). The XMPP client performs the usual service discovery by sending  disco#info packet over to the server. If any Vorpal component (external component) has web interface enabled, then it’ll reply with the disco#info packet with the following as one of its <feature>

<feature var="urn:web:interface"/>

Web interface is enabled on the component by adding vorpal.component.web.interface property to the xep-0114.xml file. This property points to the URL of the landing page for the component (like the welcome page in web.xml). For example in the Set game we have the following setting


In the tradition of Vorpal, the {__context__} is a macro for the context root (or application context)  of the WAR. Remember that even though Vorpal is not a web application, it  is packaged in a WAR file for deployment. The application server will treat it as a web application with a valid application context. So {__context__} will be replaced with the application context. The  unfortunate thing is that there is no way for me to use standard Servlet API to find out about the server portion (http://someserver:8080) at startup, so you’ll have to key this part in.

Once the XMPP client discovers that an external component supports web interface, the client will now send a <query xmlns=”urn:web:interface”/> to get the the URL of the interface. The component will now reply with the the URL. Once the client gets the URL, it then sends a HTTP GET to get the web page. See diagram above.

The Web Interface

The client exports a JavaScript object into the web interface call xmppConnection. As the name implies, this is the XMPP connection to the server. The xmppConnection object provides the following methods

xmppConnection.registerHandler(type, JavaScript_method_name) – the first parameter specifies the type of XMPP message that the JavaScript method (second parameter) should handle. The valid values for type are “message”, “presence”, “iq” and “selector”. For the second parameter, you can just enter the name of the JavaScript method name. The name has to be a String (sorry, limitation of the WebView). Say you have the following

xmppConnection.registerHandler("message", "handleMessage")

then whenever the client receives a XMPP message type, handleMessage method will be called. All JavaScript message handler has the following signature

function handlerName(msg)

where the msg is the XMPP message in String. I have written a few utilities to convert the String to XML. One of these is text2xml(). See Set Game example.

Every message send between the client and the external component is marked with the web interface’s name. This allows the XMPP client to know to which view a packet should be routed. In some cases packets arriving from some other sources that are not marked, then XMPP client will let the web view client decide if it should handle the packet. This is the “selector”. The selector behaves exactly like a message handler, has the same signature except that a message selector method returns a boolean telling the client if it wants to handle the message. If it is a true, then message will be routed to the appropriate handler.

xmppConnection.send(pkt) – sends a packet. The send() behaves like Vorpal client. It’ll try to use the default if certain information is missing from the packet eg. if you send a packet without the from, then it’ll use the current user’s name. There are also some macro from Vorpal for that you can use: {__domain__}, {__subdomain__}, {__self__}, {__username__} and {__resource__}.

xmppConnection.send(pkt, JavaScript_method_name) – If you’re sending an IQ packet and you want a specific method to handle the reply, then use this method to send. Otherwise the IQ reply will be routed to a general handler described above.

Finally, if your web page has a JavaScript function initVorpal(), then this function will be called after the HTML document have been loaded viz. if you’re using jQuery, then after $(document).ready(). initVorpal() is used to perform the web interface initialization, most notably registering message handlers. You cannot use xmppConnection until after the document has been loaded.

Set Game Web Interface

So lets look at how we go about writing a web interface by looking at an example. You can get the source here (Multiplayer Set Game). If you expand the zip file, the important files are

  • set.html – this the interface/web view for the set game
  • resources/set.js – most of the behaviour
  • resources/set.css – the stylesheet

I’ve also used

  • jQuery – for handling interaction. As it turns out jQuery is also extremely useful in manipulating and extracting information from XMPP packets
  • jStrophe – for creating XMPP message
  • vorpalutils – a set of homegrown utilities with functions culled from the Internet
    Lets walk through set.js

$(document).ready() – get jQuery to bind the action handlers to the clear, submit and refresh button. The clear button clears the Set selection; submit button sends the 3 cards that you’ve selected to the set game server in the external component and the refresh button, refreshes the 12 cards in your view. We also setup 12 blank cards

initVorpal() – does 2 things here. The first is that we setup the various message handlers.

The second is to constructs a disco#items to the JID of the subcomponent. If you recall, the first part of this describes the set game room’s name is discoverable under the external component’s JID. We set a reply handler for this IQ packet. When the reply returns (handleRoomName(msg)), the client enters the room by sending a presence packet. We get the room’s name using jQuery and then construct a presence packet with jStrophe.

Once we have joined the game room (handlePresence(msg)), we setup the set.html by displaying the number of players and also by sending a get_board message (see first part) to get the 12 cards to fill the view.

I’ve recorded a screencast of this


The latest Vorpal along with the experimental XMPP client can be downloaded from here. The Set Multiplayer can be downloaded from here. To run the XMPP client, type bin/lglass . Yeah its a bash script.

Let me know what you think.

Vorpal2 Client

Since rewriting Vorpal2 core framework, I’ve made a number of changes to the client side. I first introduce Vorpal client here; in Vorpal2 client, the programming model remains the same but bootstrapping and login in XMPP server have been change. Lets look at these changes.

Component Class

Every Vorpal application, whether its server or client side, requires a configuration file for startup. This is an XML file. The only change here is the component-class entry. This has changed from com.kenai.jabberwocky.framework.client.JabberwockyClientComponent to c.k.j.f.c.XMPPClientComponent. If you have written a client application, the following in red is what you need to change in your configuration file

<connection port=”5222″ domain=”batcomputer”>
   <component-class name=”com.kenai.jabberwocky.framework.client.XMPPClientComponent”/>
      <package name=”com.acme.xmpp.client”/>
      <property name=”vorpal.component.description” value=”A component to query the customer’s database”/>
      <property name=”” value=”Customer Query Client”/>

Bootstrapping Vorpal2 Client

A typical Vorapl2 client starts in 2 different phases; the first is to start CDI (using Weld). You can read about starting CDI in Java SE here. The second phase is to start Vorpal2 framework which will in turn start your Vorpal2 Client application. This is typically done by capturing the ContainerInitialized event.

The following code snippet shows how this is done.

@Inject ClientConnectionManager mgr;

private void containerInitialized(@Observes ContainerInitialized ciEvt) {
   String username = …
   String password = …
   ClientConnectionManager.Connection conn = mgr.createConnection();
   conn.load(new File(“client.xml”));
   if (!conn.login(username, password)) {
         //Authentication failed

   //Vorpal2 client is now started

private void containerShutdown(@Observes BeforeShutdown bsEvt) {

Once we got the ContainerInitialized event, you can create a connection from ClientConnectionManager. The ClientConnectinManager is an ApplicationScoped object which is injected into your startup class. The next step is to load the configuration file. The load() method accepts the configuration either as an InputStream, a File or a ClientComponentConfiguration object. The ClientComponentConfiguration is the object representation of the configuration file; it is JAXB enabled so you can use JAXB to unmarshall a XML configuration file. Alternatively you can also use the helper method to return an instance of ClientComponentConfiguration. read() takes either a File or an InputStream as parameter.

After successfully loading the configuration, you can now attempt to login. The login() method will return a false if it fails to login. You can optionally pass a resource into the login() method.

To close a connection, retrieve the default connection from ClientConnectionManager.getConnection() and call the logout() method.

Running Vorpal2 Client

Vorpal2 client applications are dependent on the following 4 runtime JAR files

  • vorpal2.jar
  • weld-se-core.jar
  • weld-se.jar
  • jabberwocky_support2.jar

Due to classloading issues with log4j, jabberwocky_support2.jar MUST the the last JAR file in your CLASSPATH; otherwise Weld will fail initialization.

Client support currently is still very basic. Only clear connections are supported; SSL and other features are planned.

To try Vorpal2 client support, download the latest bundle from here.

%d bloggers like this: