Debugging Maven Unit Test in Eclipse / STS

Maven unit tests (run by surefire plugin) can be debugged with eclipse. Firstly check you’re using surefire plugin version 2.16 or newer. Observe / add following in your pom.xml


Ensure you’ve set some breakpoints to debug the faulty codes. Then on your run configuration, add -Dmaven.surefire.debug=true parameter:


When this run configuration is executed, maven will wait for you to attach the remote debugger instead of launching the tests:


Now open eclipse debug configuration, create a Remote Java Application config with your source code and set the port to 5005:


When the debugger attaches the unit test will proceed and when any breakpoints hit you can debug it like a normal java/eclipse application


Debugging Event Driven Multithreaded Java Code

So here’s the scenario: you have few potentially time consuming work need to be done. They need to be executed in the order of submission, but only one work at a time can run. Simple solution is to use single thread executor.

First let’s define the Job class. This is a simple class implementing Runnable, when the job runs / stops it will print to console. A random sleep between 1 to 5 seconds is introduced to simulate some reality.

public class Job implements Runnable {

  private String id;

  public Job(String id) { = id;
  public void run() {
    System.out.println("Job " + id + " started");
    long duration = (new Random(System.currentTimeMillis()).nextInt(5) + 1) * 1000;
    try {
    } catch (InterruptedException e) {
      System.out.println("Job " + id + " interrupted");
    System.out.println("Job " + id + " completed");


To run the job I have a JobRunner class that setups the ExecutorService. Just call submit(job) and the job will be queued and run when the worker thread is free.

public class JobRunner {

  private ExecutorService executor = Executors.newSingleThreadExecutor();

  public void enqueue(Job job) {


But a debugging problem starts to appear. It is now obscure where does the code goes after calling submit()? Which thread runs it? Unless the programmer put a big comment informing it is actually a Runnable this could be very hard to guess.

Further Problems with Observer Pattern

Another common patterns often used is the observer pattern. The idea is you want specific objects to “react” when a particular event occured.

For example, let’s do two observers: OddJobObservers and EvenJobObservers. When an odd/even job completed the corresponding observer will print to console.

public class OddJobObserver implements Observer {

  public void update(Observable arg0, Object arg1) {
    int id = (int) arg1;
    if(id % 2 == 1)
      System.out.println("Odd job " + id + " completed");

public class EvenJobObserver implements Observer {

  public void update(Observable o, Object arg) {
    int id = (int) arg;
    if(id % 2 == 0)
      System.out.println("Even job " + id + " finished");


For this purpose we’ll refactor JobRunner to extend Observable so we can add the observers into it. The observer instances are created and registered on the constructor.

Each time a job is created it will also have reference back to JobRunner. We’ll also add a method jobFinished(int id) for the job to call when it’s done running.

public class JobRunner extends Observable {

  private ExecutorService executor = Executors.newSingleThreadExecutor();

  public JobRunner() {
    addObserver(new OddJobObserver());
    addObserver(new EvenJobObserver());

  public void enqueue(Job job) {

   * This will be invoked by the Job's run method in the worker thread
   * to indicate the runner that this particular job is finished
  public void jobFinished(int id) {

And on the Job class once it’s finshed running we’ll notify the observers

public class Job implements Runnable {

  // ...
  public void run() {
    System.out.println("Job " + id + " started");
    // ...

    System.out.println("Job " + id + " completed");


Consider debugging this code where you’re at the end of run() method which takes you to jobFinished(). It is now even more obscure because notifyObservers() is a Java API method, not your own code. Which code gets executed next?

Unless you did a good job on commenting, it’s very hard for someone reading your code to understand that at that point odd jobs will be observed by OddJobObserver and even jobs / EvenJobObserver.

The problem gets much worse with production client / server application with 50+ observers handling different scenario.

One approach is probably to put breakpoints on every single observers and see which one is actually “interested” in our event.

I hope this highlights how important properly commenting your code is (especially for your poor colleague who has to fix your code sometime in the future).

Java and XML Injectable Properties on Spring

Here’s how you can create a property file which can be injected on Java classes as well as on bean XML configuration file.

Firstly ensure annotation config is switched on:


Create your properties file, in this case I create on my classpath root (src/main/resources/ on Maven-compliant project)


Register this property file on your spring context using <util:properties> tag. The file will be registered as a bean class with name config

<util:properties id="config" location="classpath:/"/>

Whenever you want to inject the value into a Java class, you can use @value annotation

public class Person {

  private String name;


Similarly you can do the same to xml bean config file

<bean class="">
  <property name="name" value="#{}"/>

Note that if you config has dots on it, you need to use the square bracket syntax or Spring will confuse the dot as property access

private String name;

Multiple Environment Trick

Another trick I love is specifying multiple environment config, eg: one for prod and dev. This is common when dealing with datasource properties:


On dev environment, I then supply -Denv=dev system property to my VM args, and do this when looking up the property:

@Value("#{systemProperties['env'] == 'dev' ? config[''] : config['dbhost']}")
private String databaseHost;

Putting String List on Properties

Property files can also hold simple string list:,

When injecting this, use the split() method. Becareful with whitespaces you placed as it will be carried over

List<String> emails;

Returning JSON View on Spring MVC

Another simple way to return JSON object is by using jackson-mapper-asl. Similar to how we can map server-bound post, this method can also be used to write response.

Firstly, on your Spring MVC enabled project, add following maven dependency:


Spring can automatically convert your POJO into a json string. So say we have this data object we want to return:

public class Customer {
  private String name = "";
  private String email = "";
  // getters & setters...

And this is the controller request mapping method. Important bits here is the method returns a POJO object directly, and it is annotated with @ResponseBody annotation.

public Customer getCustomer(@PathVariable("id") long id) {
  Customer customer = // Search customer by given id through repository..
  return customer;

On the client side the returned JSON will be something like this:

  name = "Tom",
  email = ""

Prevent Tomcat From Locking WAR Files

Sometimes when Tomcat is running, although you’ve set autoDeploy to false the server process still hold file locks into the war / folder. This can be prevented by setting antiResourceLocking attribute to true on your context.xml. However the documentation said this setting might cause other issue so use it with care:

Injecting Properties to Spring MVC JSP View

Spring MVC internationalization (i18n) message support can be used for a simple config / property file. Add following bean definition on your container xml config file:

<bean class="" 

The bean above will read properties key-value pairs from WEB-INF/i18n/ Make sure you create this file with standard java-style properties:\ Bananas

Then in your JSP views, without any further intervention you can inject the values. Use spring message tag to achieve this

<%@ taglib uri="" prefix="spring" %>
    <title><spring:message code=""/></title>

Downloading Oracle JDK via Shell / Script

The most common reason you’d want to do this is if you have a remote server which you can only access via SSH. Downloading jdk first to your computer then uploading it is an option but often it’s slow. Here’s how you can download it directly from your SSH shell:

  1. Using Google Chrome browser, go to Oracle JDK download page, pick the jdk package you want to download
  2. Press F12 to open Chrome’s developer tools. Go to Network tab. networktab
  3. Accept the user agreement on Oracle’s website, and click the package link
  4. On developer tools window, find the first entry that has your package name. Right click and select Copy as cURL copycurl
  5. Now the curl command required to download the package is in your clipboard. You can paste this to your remote server’s SSH session and use it to download the package directly