Monthly Archives: March 2014

IntelliJ: Auto-generating POJO Builder

I have been searching for an elegant way to auto-generate a POJO fluent builder with minimal typing and configuration. A builder is a great way to promote object immutability, however it is also a pain to create and mantain yet another class that looks almost like the POJO class we create.

There are a few promising fluent builders out there in the wild, however, almost all of them still require some manual typing. After poking around, it seems like IntelliJ has its own fluent builder generator too.

Here’s how to do it without too much of typing…

Step 1: Define Fields in a Bean

The first step is to define the fields we need in a bean.

public class PersonBean {
    private String name;
    private LocalDate birthDate;
    private Double height;
    private Double weight;
}

Step 2: Auto-Generate Constructor and Getter Methods

The constructor and getter methods can be easily auto generated directly from IntelliJ. Do not generate setter methods.

public class PersonBean {
    private String name;
    private LocalDate birthDate;
    private Double height;
    private Double weight;
		
    public PersonBean(String name, LocalDate birthDate, Double height, Double weight) {
        this.name = name;
        this.birthDate = birthDate;
        this.height = height;
        this.weight = weight;
    }

    public String getName() {
        return name;
    }

    public LocalDate getBirthDate() {
        return birthDate;
    }

    public Double getHeight() {
        return height;
    }

    public Double getWeight() {
        return weight;
    }
		
}

Step 3: Auto-Generate Builder

Once we are satisfied with the constructor, right click on the contructor > Refactor > Replace Constructor with Builder….

In the popup dialog, click Refactor button.

By the way, if the bean allows optional fields, don’t bother hand typing the default values and checking the Optional Setter checkboxes right now because they are very tedious and they go against my “minimal typing” rule. My “Step 4” hack below will do exactly that.

IntelliJ will generate the following builder class in the same package as the POJO class:-

public class PersonBeanBuilder {
    private String name;
    private LocalDate birthDate;
    private Double height;
    private Double weight;

    public PersonBeanBuilder setName(String name) {
        this.name = name;
        return this;
    }

    public PersonBeanBuilder setBirthDate(LocalDate birthDate) {
        this.birthDate = birthDate;
        return this;
    }

    public PersonBeanBuilder setHeight(Double height) {
        this.height = height;
        return this;
    }

    public PersonBeanBuilder setWeight(Double weight) {
        this.weight = weight;
        return this;
    }

    public PersonBean createPersonBean() {
        return new PersonBean(name, birthDate, height, weight);
    }
}

Step 4: Create Nullable Fields in Builder Class

Do a regular expression “find and replace” to set null as the default value for all fields.

Find: (private \w+ \w+)(;)
Replace With: $1 = null$2

Now, we should see something like this:-

public class PersonBeanBuilder {
    private String name = null; 
    private LocalDate birthDate = null; 
    private Double height = null; 
    private Double weight = null; 

    public PersonBeanBuilder setName(String name) {
        this.name = name;
        return this;
    }

    public PersonBeanBuilder setBirthDate(LocalDate birthDate) {
        this.birthDate = birthDate;
        return this;
    }

    public PersonBeanBuilder setHeight(Double height) {
        this.height = height;
        return this;
    }

    public PersonBeanBuilder setWeight(Double weight) {
        this.weight = weight;
        return this;
    }

    public PersonBean createPersonBean() {
        return new PersonBean(name, birthDate, height, weight);
    }
}

Step 5: Reduce POJO Constructor Visibility

The very last step is to change the POJO’s public-access constructor to package-access constructor by removing public.

The key here is to have all consumers to rely on the builder class to create the POJO.

public class PersonBean {
    private String name;
    private LocalDate birthDate;
    private Double height;
    private Double weight;

    PersonBean(String name, LocalDate birthDate, Double height, Double weight) {
        this.name = name;
        this.birthDate = birthDate;
        this.height = height;
        this.weight = weight;
    }

    public String getName() {
        return name;
    }

    public LocalDate getBirthDate() {
        return birthDate;
    }

    public Double getHeight() {
        return height;
    }

    public Double getWeight() {
        return weight;
    }
}

Step 6: Using the Builder

Finally, we can use the builder class to generate the POJO:-

PersonBean personBean = new PersonBeanBuilder()
        .setName("Hulk")
        .setBirthDate(new LocalDate(1900, 12, 1))
        .setHeight(7.5)
        .setWeight(250.0)
        .createPersonBean();

Intellij v13.1 Bug: NoClassDefFoundError when Running Unit Test With JaCoCo Configured

If you are using IntelliJ and your Maven project relies on JaCoCo Maven Plugin, please consider voting up issue IDEA-122895 to get it fixed by JetBrain as soon as possible.

Even if you are not using IntelliJ or JaCoCo, but you find this shitty blog to be helpful, please consider voting up this issue to help this poor author. You will be rewarded with a thousand colorful unicorns that will help to troubleshoot your future programming obstacles.

Here’s how to do it…

Step 1

Visit IDEA-122895.

Step 2

Log into JetBrain’s YouTrack.

Step 3

Click on the vote button at the bottom of the page.

Step 4

Rejoiced! … and wait for the flying “problem-solving” colorful unicorns to arrive in 3 business days…

FindBug: Solving DM_DEFAULT_ENCODING Warning When Using FileWriter

PROBLEM

Let’s assume we have the following code to write some data into a file:-

File file = new File(someFilePath);
Writer w = new FileWriter(file);
PrintWriter pw = new PrintWriter(w);
pw.println(someContent);
pw.close();

When running this code against a static code analysis tool, such as Findbugs, we get this high priority warning:-

Found reliance on default encoding in com.choonchernlim.epicapp.CodeGeneratorService.createFile(String): 
new java.io.FileWriter(File)

Found a call to a method which will perform a byte to String (or String 
to byte) conversion, and will assume that the default platform encoding 
is suitable. This will cause the application behaviour to vary between 
platforms. Use an alternative API and specify a charset name or Charset 
object explicitly. 

The Javadoc for FileWriter says:-

Convenience class for writing character files. The constructors of this class 
assume that the default character encoding and the default byte-buffer size are 
acceptable. To specify these values yourself, construct an OutputStreamWriter 
on a FileOutputStream.

Obviously, this class is too convenient and FindBugs is not happy about it. Further, there is no way to set a charset using FileWriter.

SOLUTION

To make FindBugs as happy as Pharrell Williams, we can use OutputStreamWriter instead because it allows us to specify a charset.

File file = new File(someFilePath);
Writer w = new OutputStreamWriter(new FileOutputStream(file), "UTF-8");
PrintWriter pw = new PrintWriter(w);
pw.println(someContent);
pw.close();

Knowns and Unknowns

There are known knowns. These are things we know that we know. There are known unknowns. That is to say, there are things that we know we don’t know. But there are also unknown unknowns. There are things we don’t know we don’t know.

– Donald Rumsfeld

Maven: Excluding All Transitive Dependencies

I have been using Maven 3.0.3 on my work machine since 2011 because that particular version was released in March that year. How time flies by…

Maven 3.2.1 was released exactly a month ago. One feature that immediately jumps out is the ability to exclude a dependency’s transitive dependencies in a very simple manner, which is incredibly sweet and tasty.

Instead of manually excluding each transitive dependency one by one, we can use * wildcard now. Here’s an example from the release note:-

<?xml version="1.0"?>
<dependencies>
  <dependency>
    <groupId>org.apache.maven</groupId>
    <artifactId>maven-embedder</artifactId>
    <version>3.1.0</version>
    <exclusions>
      <exclusion>
        <groupId>*</groupId>
        <artifactId>*</artifactId>
      </exclusion>
    </exclusions>
  </dependency>
  ...
</dependencies>

Okay, I have made an executive decision here… that I’ll upgrade Maven on my work machine to this latest version.

Comparing Disassembled Java Class From JVM Languages

All JVM languages come with some degrees of syntactic sugar to make the code easier to read and write.

To satisfy my curiosity, I decided to run javap command to disassemble the bytecode inside the class file generated from several JVM languages. The chosen languages are Java, Groovy, Scala, JRuby and Rhino. I left out Clojure because the syntax does not compute for me after having my heavy lunch.

JAVA

Source Code

public class JavaPerson {
    private String name;
    private int age;

    public JavaPerson(String name, int age) {
        this.name = name;
        this.age = age;
    }

    public String getName() {
        return name;
    }

    public int getAge() {
        return age;
    }
}

Disassembled Java Class

public class com.choonchernlim.epicapp.JavaPerson {
  public com.choonchernlim.epicapp.JavaPerson(java.lang.String, int);
  public java.lang.String getName();
  public int getAge();
}

GROOVY

Source Code

class GroovyPerson {
    String name
    int age
}

Disassembled Java Class

public class com.choonchernlim.epicapp.GroovyPerson implements groovy.lang.GroovyObject {
  public static transient boolean __$stMC;
  public static long __timeStamp;
  public static long __timeStamp__239_neverHappen1395328777863;
  public com.choonchernlim.epicapp.GroovyPerson();
  public java.lang.Object this$dist$invoke$1(java.lang.String, java.lang.Object);
  public void this$dist$set$1(java.lang.String, java.lang.Object);
  public java.lang.Object this$dist$get$1(java.lang.String);
  protected groovy.lang.MetaClass $getStaticMetaClass();
  public groovy.lang.MetaClass getMetaClass();
  public void setMetaClass(groovy.lang.MetaClass);
  public java.lang.Object invokeMethod(java.lang.String, java.lang.Object);
  public java.lang.Object getProperty(java.lang.String);
  public void setProperty(java.lang.String, java.lang.Object);
  public static void __$swapInit();
  static {};
  public java.lang.String getName();
  public void setName(java.lang.String);
  public int getAge();
  public void setAge(int);
  public void super$1$wait();
  public java.lang.String super$1$toString();
  public void super$1$wait(long);
  public void super$1$wait(long, int);
  public void super$1$notify();
  public void super$1$notifyAll();
  public java.lang.Class super$1$getClass();
  public java.lang.Object super$1$clone();
  public boolean super$1$equals(java.lang.Object);
  public int super$1$hashCode();
  public void super$1$finalize();
  static java.lang.Class class$(java.lang.String);
}

SCALA

Source Code

class ScalaPerson(val name: String, val age: Int) {
}

Disassembled Java Class

public class ScalaPerson {
  public java.lang.String name();
  public int age();
  public ScalaPerson(java.lang.String, int);
}

JRUBY

Source Code

require 'java'

class JRubyPerson
  java_signature 'JRubyPerson(String, int)'
  def initialize (name, age)
    @name= name
    @age = age
  end

  java_signature 'String getName()'
  def name;
      @name
  end

  java_signature 'int getAge()'
  def age;
    @age
  end
end

Disassembled Java Class

public class JRubyPerson extends org.jruby.RubyObject {
  public static org.jruby.runtime.builtin.IRubyObject __allocate__(org.jruby.Ruby, org.jruby.RubyClass);
  public JRubyPerson(java.lang.String, int);
  public java.lang.String getName();
  public int getAge();
  static {};
}

RHINO

Source Code

function RhinoPerson( name, age ) {
    this.name = name;
    this.age = age;

    this.getName = function () {
        return this.name;
    };

    this.getAge = function () {
        return this.age;
    };
}

Disassembled Java Class

public class RhinoPerson extends org.mozilla.javascript.NativeFunction implements org.mozilla.javascript.Script {
  public RhinoPerson(org.mozilla.javascript.Scriptable, org.mozilla.javascript.Context, int);
  public RhinoPerson();
  public static void main(java.lang.String[]);
  public final java.lang.Object exec(org.mozilla.javascript.Context, org.mozilla.javascript.Scriptable);
  public final java.lang.Object call(org.mozilla.javascript.Context, org.mozilla.javascript.Scriptable, org.mozilla.javascript.Scriptable, java.lang.Object[]);
  public int getLanguageVersion();
  public java.lang.String getFunctionName();
  public int getParamCount();
  public int getParamAndVarCount();
  public java.lang.String getParamOrVarName(int);
  public java.lang.String getEncodedSource();
  public boolean getParamOrVarConst(int);
}

Spring: Choosing the Right Dependency Injection Approach

There are many different ways to perform dependency injection (DI) in Spring. As Spring evolves over time, the DI configuration also changes over time, which may contribute to some confusion to those who are just learning Spring.

Scenario

Let’s assume we have this scenario: We have Team Awesome that consists of one awesome member, called Donkey Hulk. Donkey Hulk can only do two things: walk and smash. When someone calls Team Awesome for help, Donkey Hulk will walk around and smash stuff. Okay, I’m very tired this early AM, but you get the point here…

Once we have configured the dependency injection, we are going to use the code below to call for help.

public class Main {
    public static void main(String[] args) {
        ApplicationContext context = new ClassPathXmlApplicationContext("applicationContext.xml");
        TeamAwesome teamAwesome = context.getBean(TeamAwesome.class);

        System.out.println(teamAwesome.rescue());
    }
}

Solution #1: Solving with Angular Stuff

… and no, I’m not referring to AngularJS. Rather, I’m talking about angle brackets here, also known as XML.

To accomplish DI using XML, we created DonkeyHulk class…

public class DonkeyHulk {
    public String walk() {
        return "DonkeyHulk walks slowly.";
    }

    public String smash() {
        return "DonkeyHulk smashes some pumpkins.";
    }
}

… and created TeamAwesome class…

public class TeamAwesome {
    private DonkeyHulk donkeyHulk;

    public void setDonkeyHulk(DonkeyHulk donkeyHulk) {
        this.donkeyHulk = donkeyHulk;
    }

    public String rescue() {
        return donkeyHulk.walk() + " " + donkeyHulk.smash();
    }
}

Finally, we use XML to wire them up.

<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
       xsi:schemaLocation="
       http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd">

    <bean id="donkeyHulk" class="com.choonchernlim.epicapp.service.DonkeyHulk"/>

    <bean id="teamAwesome" class="com.choonchernlim.epicapp.service.TeamAwesome">
        <property name="donkeyHulk" ref="donkeyHulk"/>
    </bean>
</beans>

Solution #2: @Service and @Autowired

Realizing all the XML mess, Spring 2.5 introduced several useful annotations, most importantly @Autowired and @Service.

With these annotations, we essentialy cut down the XML configurations down to one line:-

<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
       xmlns:context="http://www.springframework.org/schema/context"
       xsi:schemaLocation="
       http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd
       http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context.xsd">

    <context:component-scan base-package="com.choonchernlim.epicapp"/>
</beans>

For DonkeyHulk class, all we need to do is to annotate the class with @Service annotation so that the component scan is aware of this Spring bean.

@Service
public class DonkeyHulk {
    public String walk() {
        return "DonkeyHulk walks slowly.";
    }

    public String smash() {
        return "DonkeyHulk smashes some pumpkins.";
    }
}

Now, this is where things get a little tricky, especially for those who are just learning Spring. The @Autowired annotation allows you to autowire a bean at the field level, method level or constructor level.

Solution #2a: @Autowired at Field Level

This is probably the simplest way to inject a dependency into a class. All we do here is to create a field and annotate it with @Autowired. It can’t get any simpler than this.

@Service
public class TeamAwesome {
    @Autowired
    private DonkeyHulk donkeyHulk;

    public String rescue() {
        return donkeyHulk.walk() + " " + donkeyHulk.smash();
    }
}

While this may seem like an elegant piece of code, the biggest downside to this approach is there’s no way we can mock the injected dependency in our test cases. Donkey Hulk may take one minute to walk before it starts smashing, and everytime we test Team Awesome, we have to suffer through and wait for Donkey Hulk to do its job.

That said, this approach works, if:-

  • The injected dependency is relatively fast.
  • The injected dependency does not interact with external system(s).
  • You don’t write test cases.

Solution #2b: @Autowired at Method Level

To fix the above problem, we can perform the dependency injection at the method level.

@Service
public class TeamAwesome {
    private DonkeyHulk donkeyHulk;

    @Autowired
    public void setDonkeyHulk(DonkeyHulk donkeyHulk) {
        this.donkeyHulk = donkeyHulk;
    }

    public String rescue() {
        return donkeyHulk.walk() + " " + donkeyHulk.smash();
    }
}

With this approach is we can mock (or spy) Donkey Hulk and make it walk faster.

The downside to this approach is it doesn’t look “semantically” correct, especially for those who comes from the Object Oriented (OO) world. Let’s assume the Team Awesome now consists of three members:-

@Service
public class TeamAwesome {
    private DonkeyHulk donkeyHulk;
    private SpiderPig spiderPig;
    private NinjaTortoise ninjaTortoise;

    @Autowired
    public void setDonkeyHulk(DonkeyHulk donkeyHulk) {
        this.donkeyHulk = donkeyHulk;
    }
		
    @Autowired
    public void setSpiderPig(SpiderPig spiderPig) {
        this.spiderPig = spiderPig;
    }
		
    @Autowired
    public void setNinjaTortoise(NinjaTortoise ninjaTortoise) {
        this.ninjaTortoise = ninjaTortoise;
    }

    public String rescue() {
        return ...;
    }
}

See the problem here? The OO programers are taught to create objects using constructors and the constructor’s job is to contruct the object. Now, there are all these setter methods that “seem” to violate the principle of immutability. Further, these setter methods tend to clutter our otherwise perfect code.

Solution #2c: @Autowired at Constructor Level

A much better approach is to perform the dependency injection at the constructor level.

@Service
public class TeamAwesome {
    private DonkeyHulk donkeyHulk;

    @Autowired
    public TeamAwesome(DonkeyHulk donkeyHulk) {
        this.donkeyHulk = donkeyHulk;
    }

    public String rescue() {
        return donkeyHulk.walk() + " " + donkeyHulk.smash();
    }
}

Even for those who don’t know Spring, by inspecting the constructor, they know that Team Awesome requires Donkey Hulk for it to work.

Going back to the previous example where Team Awesome has three members, it is as easy as passing them into the same constructor.

@Service
public class TeamAwesome {
    private DonkeyHulk donkeyHulk;
    private SpiderPig spiderPig;
    private NinjaTortoise ninjaTortoise;

    @Autowired
    public TeamAwesome(DonkeyHulk donkeyHulk, 
                       SpiderPig spiderPig, 
                       NinjaTortoise ninjaTortoise) {
        this.donkeyHulk = donkeyHulk;
        this.spiderPig = spiderPig;
        this.ninjaTortoise = ninjaTortoise;
    }

    public String rescue() {
        return ...;
    }
}

What if we have two implementations of Donkey Hulk: the default implementation and a faster implementation of Donkey Hulk? We still can choose which implementation to use with @Qualifier annotation without affecting other injected dependencies.

@Service
public class TeamAwesome {
    private DonkeyHulk donkeyHulk;
    private SpiderPig spiderPig;
    private NinjaTortoise ninjaTortoise;

    @Autowired
    public TeamAwesome(@Qualifier("fasterDonkeyHulk") DonkeyHulk donkeyHulk, 
                       SpiderPig spiderPig, 
                       NinjaTortoise ninjaTortoise) {
        this.donkeyHulk = donkeyHulk;
        this.spiderPig = spiderPig;
        this.ninjaTortoise = ninjaTortoise;
    }

    public String rescue() {
        return ...;
    }
}

Solution #3: Solving with @Configuration

What if you are so-called “Java purist” and you hate to see your project code cluttered with Spring annotations?

The good news is Spring 3.0 introduced @Configuration annotation that allows us to use Java-based configuration.

Both DonkeyHulk and TeamAwesome look like regular Java code.

public class DonkeyHulk {
    public String walk() {
        return "DonkeyHulk walks slowly.";
    }

    public String smash() {
        return "DonkeyHulk smashes some pumpkins.";
    }
}

public class TeamAwesome {
    private DonkeyHulk donkeyHulk;

    public TeamAwesome(DonkeyHulk donkeyHulk) {
        this.donkeyHulk = donkeyHulk;
    }

    public String rescue() {
        return donkeyHulk.walk() + " " + donkeyHulk.smash();
    }
}

Then, we create a separate configuration class annotated with @Configuration that contains the dependency injection configurations.

@Configuration
public class MyConfiguration {

    @Bean
    public DonkeyHulk getDonkeyHulk() {
        return new DonkeyHulk();
    }

    @Bean
    public TeamAwesome getTeamAwesome(DonkeyHulk donkeyHulk) {
        return new TeamAwesome(donkeyHulk);
    }
}

The downside to this approach is… well, let me tell a story here…

… Once upon a time, we the Java developers liked to hardcode our configurations in the Java code. Then, someone said “That’s a BAD idea and we should externalize them into a flat file!”. As we looked for a solution, we stumbled upon something called the dot properties file. Then, someone said “This key-value pair structure is too simple, and we can’t group things nicely!”. Then, we stumbled upon the epic angle brackets called the Extensible Markup Language. As years passed by, the project scope got larger, and we the Java developers spent more time managing XML code than Java code. The Ruby developers laugh at us and our pride hurt for many years. Then, the annotation-based configuration saved the day and we lived happily ever since. Not too long ago, somebody with too much of free time decided to come up with Java-based configuration to completely eliminate all the remaining XML-based configuration. We the Java developers celebrated and rejoiced for the epic discovery. Then, wait… WTF?? Are we repeating the history here??

For the record, there are many important uses of Java-based configuration especially when dealing with configurations that has to be determined at runtime. However, this example of Team Awesome is not one of them.

What’s My Take?

My take is to use @Autowired at the constructor level 90% of the time. Then, depending on the problem set, I may use XML-based configuration or Java-based configuration where I deem fit.