Context Dependency Injection

The Java EE programming model has been simplified substantially since J2EE. Annotations have replaced the XML description files, convention over configuration have replaced the tedious manual configuration and dependency injection hides the creation and look up of resources.

Resources are created and injected at injection points marked by annotations such as @Inject. All you need is a POJO that meets all of the conditions of the managed beans specification JSR 299 and depending on the annotation used it will become an EJB, servlet, singleton or RESTful web service.

The object is injected by the container and is determine by type. However using an interface as a type can confuse the container if there is more than one concrete implementation. It doesn’t know which object to inject. This confusion can be resolved by the use of a qualifier annotation that marks the concrete implementation you want to implement. We will see how this annotation is used with @Producer in the implementation of the factory pattern. Beans or objects that you want to inject that do not conform to JSR299 use the @Producer annotation to make them injectable.

JSR 299 Managed bean specification

It is not a nonstatic inner class.

It is a concrete class or is annotated @Decorator.

It is not annotated with an EJB component-defining annotation or declared as an EJB bean class in ejb-jar.xml.

It has an appropriate constructor. That is, one of the following is the case:

The class has a constructor with no parameters.

The class declares a constructor annotated @Inject.

No special declaration, such as an annotation, is required to define a managed bean.
To enable CDI you must have a beans.xml file in your project (under the META-INF or WEB-INF).

The beginning of Design Patterns

The beginning

Did they just appear overnight? Where did they come from? In fact design patterns have a long history starting way before computing, in architecture. That’s the construction type of architecture. But it wasn’t really until the GOF wrote their seminal book Design patterns, that the concept of design patterns was cemented in the world of Java. The book introduces a list of design patterns categorised under three titles: creational, behavioural and structural.

Design patterns are solutions to problems already solved. They represent the collective wisdom of developers and provide us with a common vocabulary. By implementing solutions that are proven to work we avoid reinventing the wheel and can focus our efforts on solving the other problems we will face as we develop our application. However, we need to take care not to overuse design patterns. Unnecessary use of patterns tends to overcomplicate code making it hard to maintain and a poor design pattern knowledge leads to the inappropriate implementation of patterns to problems that they were not designed to solve. It is very much the case that: If the only tool you have is a hammer, then you will see every problem as a nail.

The book’s authors are Erich Gamma, Richard Helm, Ralph Johnson and John Vlissides.

Java 8 Streams: .filter and predicate negation

Recently there was an interesting discussion on the use of predicate negation in the .filter method on a stream by members of the LJC mailing list, so I thought it would be worth summarising it in a blog post. The discussion was about ways to use .filter and to negate the predicate.

Code for this post is available in my github account.

This is perhaps how you might think about doing, but here are some alternative ways.

Stream.of(1, 2, 3, 4, 5, 6, 7)
      .filter(((Predicate) c -> c % 2 == 0).negate())

Answer 1: Write a predicate utility method

You can simplify this by writing a utility method that performs the negation.

public static <R> Predicate<R> not(Predicate<R> predicate) {
      return predicate.negate();

Which results in much neater code.

Stream.of(1, 2, 3, 4, 5, 6, 7)
      .filter(not(c -> c % 2 == 0))

View source on github

Answer 2: Use an identity function to convert the method reference to a Predicate

We use a utility method to convert a method reference to a predicate.

public static <T> Predicate<T> predicate(Predicate<T> predicate) {
      return predicate;

although the code is not as neat.

Stream.of("Cat", "", "Dog")

References: Heinz’s Lambda Reduction Principle

Answer 3: Use the not (!) operator

Use the familiar not operator.

Stream.of(1, 2, 3, 4, 5, 6, 7)
      .filter((c -> c % 2 != 0))

Stream.of("Cat", "", "Dog")
      .filter(str -> !str.isEmpty())

The code is much simpler and immediately familiar.

It is argued that method references are often harder to read and are trickier when refactoring than simple lambdas and that that mixing lambdas and method references in a Stream chain is confusing to the reader. Reference: Java SE 8 Best Practices

When you use a method reference and want the IDE to create the method, IntelliJ creates this as a static method with the object as the first argument. Using the not operator avoids this.

Here are some useful references:

Cross-platform mobile developement

So what problems does cross-platform development actually solve. well they are two-fold.


  • To have the capability of complete (or near complete) mobile platform coverage by developing the application once to run on multiple platforms. To kill two (or multiple birds) with one stone.

killing two birds 1

  • And secondly to reduce language selection to a subset of the languages normally used to develop mobile applications and ideally to just one.

langiage choose

The financial implication of successful cross-platform development are obvious in terms of human resources and clearly make this kind of development very attractive to businesses and their clients.

Two Approaches

There are two broad approaches to developing for multiple platforms. The Hybrid approach, used by the GWT, where the code is developed in one language only (in the case of gwit it is Java) and then translated to HTML5, CSS and javascript. These apps run the same code on every platform and render views in the webview of the native device. Access to device features such as the camera and contacts leverage JSNI (JavaScript native interface), perhaps using Cordova.
 1001.sdt-apache-cordova html5 logo-sencha
The alternative approach is to cross-compile your code base to the native code of the target device by translating to the native language. Weather that be Swift/Objective-c for iOS or Java on Anroid or C# on windows phone.
 swift-ogjava androidobjective-cvisualcsharp_2
We are gong to look at three frameworks that levarage these methods but in quite unique ways.


tabbris websiteTabris falls into the Hybrid category of cross-platform development. Like GWT it uses Java to describe the views and widgets available to the application and Java EE technology to create an application on the server. However unlike gwit it does not translate the UI into HTML5 and JavaScript but rather into JSON representations of the UI element. The native client effectively acts as a player for the applications UI. It access the application by calling a URL that provides the JSON representation of the UI element. Then the client will render the UI from the JSON message using native components. For iOS those components are Cocoa Touch widgets and Java based widgets for Andriod.
On the server side a war file is deployed to a web server where it registers a servlet that becomes the entry point of the application. The JSON UI messages are then served to the client.
You require a commercial license to use their framework.
OK so lets see how this works from a code perspective. The Tabris UI framework is responsible for creating the Page and
tabris code example ui 2 Action objects which are added to the UI Configuration object. in this example two configurations will be created and added to the UIConfiguration. The first is a PageConfiguration which defines a top level page with id ‘all-dvds’ .This page will have a title and an image. The second configuration is an ActionConfiguration that defines a search action. This is then rendered with the native look and feel.
areas IOS Native Screen Shot

Codename One

codename one websiteNow lets have a look at a framework that compiles java code to the native language of the target device. Codename one comes as a plug-in for eclipse, netbeans and intillij. Using their API you build your app’s UI and code its business logic. The interesting part comes when you want to compile and deploy the app code.
For apps written to directly target an Android, J2ME & Blackberry device the standard Java code is executed as is. While apps coded in Java 5 are translated to JDK 1.3 cldc subset for execution on J2ME and Blackberry. For target iOS devices the java  code is translated to C code and for the Windows phone it is translated to c#.
Now the really interesting part here is that to compile to native code you select the target device from the plugin menu, this bundles the app and sends the code off to thier remote build servers where it uses a virtual mac or pc to perform the necessary actions to compile the code.
This removes the need to own a mac and pc machine. When the app is compiled and is ready you are presented on screen with a QR code that when scanned by your device will download and install the app.
condename one code exampleNow lets see some code. For those of you who know Swing or even GWT, for that matter, this code will be immediately understandable. Page components are created and action listeners are attached as anonymous classes. In the example we create a button and add it as a component to the form.  Then we add an action listener to the button.
When the button is click a dialog box pops up showing the message.
They published a blog article a few months ago saying that they are working on java 8 for the next plugin release. So we should see code like this in the future.condename one code example java 8
You require a commercial license to use their framework.

Oracle mobile application Framework

maf websiteAnd finally lets take a look at Oracle’s offering. They have taken a very different approach to the other two. You write your business logic and the code that reacts to user interactions and accesses backend functions. This code is then deployed on a lightweight native JVM on each device. The JVM is bound to the webview and device features.
The UI components are defined in XML, HTML 5 or can be served as HTML webpages. Devices maf architecturefeature’s interactions leverage Apache cordova and are rendered in the native webview.
However you must use either Eclipse or JDeveloper.
MAF flow controlLets look at how a MAF app is developed. The flow between pages is defined with the help of a GUI that visually represents the pages and their inter-relationships, here showGraph specifies the transition type, you then must write the actual logic for each page.
The device’s features are accessed via an instance of the DeviceManager. maf - accessing contactsHere we create a new contact and added it to the contacts via the devicemanager. Your app is deployed as a platform specific deployment.
And a commercial license is required to use the framework.
The slides to the complete JavaOne presentation that I did with Murat can be downloaded from slide share: Mobile Java with GWT: Still “Write Once, Run Everywhere”

RabbitMQ cluster on a single machine

If you are having problems setting up a cluster on a single machine then the following post might help answer some questions.

I assume that you have already set up RabbitMQ on your local machine (rabbit@localhost) and want to know how to add two more nodes and cluster them.

These instructions relate to the installation on a MacBook Pro running OS X Yosemite.

As you already have an installation of RabbitMQ all you need to do is instantiate instances on new nodes. The following command will instantiate an instance of Rabbit on a node called hare@localhost.

        rabbitmq-server &amp;

Ensure the port number is different to the port currently in use.

A sticking point are the ports bound by Rabbit to plug-ins. You might see the following error:


Error description:

This means that the Rabbit MQTT for the currently running node is using port 1883.


Error description:

This means that the Rabbit STOMP for the currently running node is using port 61613.

To resolve this conflict add an argument to RABBITMQ_SERVER_START_ARGS specifying a new port for the plug-in.

A list of installed plug-in is shown in the RabbitMQ web interface in the overview tab under ports and contexts.

The following shows how to configure ports for the Rabbit management and Rabbit MQTT

        -rabbitmq_management listener [{port,15674}] 
        -rabbitmq_mqtt tcp_listeners [1884]" 
    rabbitmq-server &amp;


Now add the node to the cluster. Stop the instance, join it to another node and start.

rabbitmqctl -n hare@localhost stop_app

rabbitmqctl -n hare@localhost join_cluster rabbit@localhost

rabbitmqctl -n hare@localhost start_app







DevoxxUK & JavaDay Lviv Presentation write up

Thank you to all those who attend my presentations at JavaDay Lviv and DevoxxUK. I have written up my notes from the two presentations. DevoxxUK & JavaDay Lviv Presentation write up. The Lviv presentation video can be viewed here: Java EE changes design pattern implementation.

Devoxx UK 2015: How Java EE has changed design pattern implementation

Thank you to all who attended my quickie talk at Devoxx UK today. Here are the slides from my presentation. If you would like to purchase a copy of our book entitled: Professional Java EE design patterns which covers all topics from my talk and much more you can get a 40% discount with promo code VBK43 when ordering through valid until 1st September. The Lviv presentation video can be viewed here: Java EE changes design pattern implementation.