HK2 injection in Standalone Java Application with Custom Binder

In my previous post, I gave an example of using the HK2 injection in a stand-alone application.

Please refer it in the below link.
Hk2 Injection with hk2 inhabitant file

In the above example, we have to create an HK2 inhabitant file which contains the binding information such as contract and service name and their mapping. The overhead in this approach is generating the HK2 default file. We can automate the file creation process in the maven build with hk2-inhabitant-generator plugin. But at some point, we may want to define the mapping explicitly such as using the service and contract from different libs. The hk2-inhabitant-generator may not add the contract/service mapping in the inhabitant file. Therefore, to resolve the above problem, we need to define a custom binder which contains all the bindings details.

Let’s see how can use the HK2 injection in a stand-alone application with a custom binder.

The below one is my POM file.

We have a standalone application which will be used for adding, deleting, updating the user details into HashMap or Google Guava Cache. We have two interfaces(UserService for service and UserDao for DAO) and three implementation classes(UserServiceImpl, UserGuavaCacheImpl and UserLocalCacheDaoImpl)

UserGuavaCacheImpl is used to do CRUD operation on Guava Chache and UserLocalCacheDaoImpl is used to do CRUD operation on HashMap.

We decide to use either Local cache or Google Guava cache based on a system property. This is a simple example to show how we can use the HK2 injection.
Refer the below image to know my project structure.


All our interfaces should be annotated with @Contract and all the implementation classes should be annotated with @Service.

Refer below my Service implementation.

Refer my various DAO implementations below.

Refer my custom binder file which has the binding information below.


In the above file, I have used “Named” annotation as we have two services for UserDao interface. If we don’t provide that then by default, the service locator injects the first available implementation.

Below is my main class which invokes the User Service to perform various CRUD operations with User Object.
The below code is used to create a ServiceLocator instance and then we bind the created service locator with our custom binder.

ServiceLocator serviceLocator = ServiceLocatorFactory.getInstance().create("serviceLocator");
ServiceLocatorUtilities.bind(serviceLocator, new DependencyBinder());

We can use the ServiceLocator object for getting the Object instance like below

UserService userService = serviceLocator.getService(UserService.class, "empService");

We have two DAO implementation. We need to decide which one to use. The hk2 IterableProvider will give both the implementations classes. Therefore, I have used a system property to decide the appropriate cache implementation. Refer the below code from UserServiceImpl.

    public UserServiceImpl(IterableProvider iterableProviders) {
        String cache = System.getProperty("CACHE");
        if ( {
            this.userDao = iterableProviders.named("empGuavaCacheDao").get();
        else if( {
            this.userDao = iterableProviders.named("empLocalCacheDao").get();

The output of my program is as given below,

Add user details
The user details after it has been added User: User{id='0701f22b-10b0-4d6f-8c8d-410da89646f9', firstName='First Name', lastName='Last Name}
Now fetch the user details with ID
User :User{id='0701f22b-10b0-4d6f-8c8d-410da89646f9', firstName='First Name', lastName='Last Name}
Now update the user details
User After Updation:User{id='0701f22b-10b0-4d6f-8c8d-410da89646f9', firstName='Bala', lastName='Samy}
Now delete the user details
User After Deletion:null

Testing HK2 injection
Fetching the various DAO implementation
UserDao userDao = serviceLocator.getService(UserDao.class, "empGuavaCacheDao")
userDao instanceof UserGuavaCacheImpl - > Its an instance of UserGuavaCacheImpl 
userDao = serviceLocator.getService(UserDao.class, "empLocalCacheDao")
userDao instanceof UserLocalCacheDaoImpl - > Its an instance of UserLocalCacheDaoImpl 


Refer the code @hk2-java-custombinder



How to use Oracle XMLTable syntax

I have got a requirement to query against a XMLTYPE content and fetch the records from it.

XMLTable maps the result of an XQuery evaluation into relational rows and columns. So I am going to use this here.

Assume that we have a table called user_events which has two columns event_data and event_date. event_data is a XMLTYPE column. Now I want to query the user_events table and find out the list of users who have used the system for Jan month.

Here is the syntax.

select distinct userName from user_events e,
XMLTABLE ('user_events'
        PASSING e.event_data
        COLUMNS userName  VARCHAR2(50) PATH '/events/user/userName', 
                userId VARCHAR2(10) PATH '/events/user/userId')
where event_date >= '01-JAN-18' AND event_date <= '31-JAN-18'
order by userName asc; 

docker installation in ubuntu

The below steps are for installing the specific version of docker-ce in ubuntu

1. Run the below command to download the package.


2. Run the below command to install the same.
sudo dpkg -i docker-engine_17.05.0~ce~rc3-0~ubuntu-trusty_amd64.deb

The below steps are for installing the docker engine in ubuntu

1. Run the below command to find out the available version
sudo apt-cache showpkg docker-engine

2. Then select the specific version and run below to install the docker-engine. The below one is used to install 1.13.1 version of docker-engine. 
sudo apt-get install docker-engine=1.13.1-0~ubuntu-trusty

How to use Maven Shade Plugin

Maven Shade Plugin provides the capability to package the artifact in an uber-jar, including its dependencies and to shade(rename) the packages of some of the dependencies.

This plugin is used to take all the dependencies and extract the content and put them as is and create one big JAR(Uber. This will be good for runnable jar but if you are planning to use this jar as a maven dependency then there may be some conflicts with the client jar. So we need to use the relocations option to relocate the conflicting classes to a different package.

In this post, I will show how to use this plugin with an example.

The below example is for creating the final Uber jar without relocations.

Create Uber Jar without relocations

Consider that we have a web app which exposes a REST web service and running on a grizzly container. Now, let’s use the shade plugin to create the fat jar.

I am not going to give the code examples here as this post explains about the shade plugin only.

Refer the complete code

The below plugin configuration has to be added in the maven pom file.

Refer the configuration section where we have to specify various options. They are given below,

  • mainclass – The entry point of the application
  • createSourcesJar – Create the sources jar as well
  • shadedClassifierName – The name of the classifier used in case the shaded artifact is attached
  • shadedArtifactAttached – It defines whether the shaded artifact should be attached as classifier to the original artifact. If its false, then the original jar will be replaced by the shaded jar

					<transformer implementation="org.apache.maven.plugins.shade.resource.ManifestResourceTransformer">

Then execute ‘mvn package’ command and then check the target folder. You will be able to see the shaded jar and it ends with shaded suffix. Refer the below screenshot.


When you extract out the contents of the shaded jar, you will see below.


Create Uber Jar with relocations

Now we are going to see how we can relocate some of the classes inside the Uber Jar. Lets use the same example and add the below relocations inside the configuration element.

		<transformer implementation="org.apache.maven.plugins.shade.resource.ManifestResourceTransformer">

Check the element and the child elements. Here, I am planning to rename/move the org.glassfish.grizzly.utils package to org.shaded.glassfish.grizzly.utils and exclude the package org.glassfish.grizzly.utils.conditions.

Then run the mvn package again to create the shaded jar and extract out the contents of the shaded jar. It will look like below.


As you can see that the package org.glassfish.grizzly.utils has been moved to org.shaded.glassfish.grizzly.utils but the inner package org.glassfish.grizzly.utils.conditions has been kept it as in the oringal location.

While relocating the packages, this plugin will also update the affected bytecode. So you will not see any issues while running the Uber jar.

Ruby Rails test error “warning: constant :: Fixnum is deprecated”

I got the below error while trying to run the Ruby Test case in Ubuntu VM.

Error Trace:

/home/bala/.rvm/gems/ruby-2.4.1/gems/watir-webdriver-0.9.3/lib/watir-webdriver/elements/html_elements.rb:17: warning: constant ::Fixnum is deprecated

Follow the below steps to get rid of the above error.

1. Uninstall Rails completely. Execute the below commands one by one.

   gem uninstall rails
   gem uninstall railties

2. Then run the below command to install the rails.

gpg --keyserver hkp:// --recv-keys 409B6B1796C275462A1703113804BB82D39DC0E3
\curl -sSL | bash -s stable --rails

3. Update the watir version in my Gemfile to 6.1 from 5.0.0

4. Then run the below command and then run your test case.

  bundle install

Exclude fields from Serialization with GSON API

GSON is a Java serialization/deserialization library to convert Java Objects into JSON and back.

In this post, we are going to see how we can exclude some fields from serialization with the GSON API.

Refer the below model class.

import org.apache.commons.lang3.builder.ToStringBuilder;

public class Employee {

    private String firstName;
    private String lastName;
    private int salary;

    public String getFirstName() {
        return firstName;

    public void setFirstName(String firstName) {
        this.firstName = firstName;

    public String getLastName() {
        return lastName;

    public void setLastName(String lastName) {
        this.lastName = lastName;

    public int getSalary() {
        return salary;

    public void setSalary(int salary) {
        this.salary = salary;

    public String toString() {
        return ToStringBuilder.reflectionToString(this);

The above Employee class has three fields such as first name, last name and salary. Consider that we want to exclude the salary field while serializing the employee object.

To do so, then we have to create a class which implements the ExclusionStrategy interface and provide our logic over there.


public class SalaryExclusionStrategy implements ExclusionStrategy {

    public boolean shouldSkipField(FieldAttributes f) {
        return "salary".equalsIgnoreCase(f.getName());

    public boolean shouldSkipClass(Class clazz) {
        return false;

We need to instruct the GSON parser to ignore the salary field. So while creating the GSON object, we have to pass an instance of SalaryExclusionStrategy which contains the logic to ignore the salary field to the addSerializationExclusionStrategy method.

Refer the below code to know how we can do that.


public class GsonMain {

    private static final Gson GSON = new GsonBuilder()
            .addSerializationExclusionStrategy(new SalaryExclusionStrategy())

    public static void main(String[] args) {
        Employee employee = new Employee();

Refer below the output.

  "firstName": "Bala",
  "lastName": "Samy"