Thursday, May 29, 2014

Regex to replace upper case with lower case in UltraEdit

Regex in UltraEdit to replace someStringWithCamelCase with "some string with camel case".

This is using regex to find upper case characters and replace them with lower case by finding ([A-Z]) and replacing with \L\1\E.

Thanks to this StackOverflow post: Convert a char to upper case using regular expressions (EditPad Pro).

Saturday, March 22, 2014

Listary, Directory Opus and AutoHotkey - a match made in Geek Heaven

Listary is a very good tool for finding files fast. It indexes all drives on your machine and integrates into Windows Explorer or Directory Opus (my explorer of choice) so that when you start typing any file name, it will straight away show you all matches, highlighting the ones in your current directory.

You can also set a hotkey to summon a Listary toolbar if you are not in a file explorer to do the same thing - search for files. What is so cool about this is that once you find the file you want, press the right arrow key and you have the context menu displayed, so you can choose to open the file, do an SVN update or whatever - without having to go to your explorer program. There are other options added too - like copying the path of the file/directory to clipboard.

The free and pro versions are the same download - and you can access many of the pro features while using it for free (with a not very intrusive nag dialog). However, the pro version is well and truly worth it: $20 for lifetime upgrades.

As I mentioned, Directory Opus is my file explorer tool of choice, and I will often use the Listary toolbar to find and go to a directory when Directory Opus is open but not in focus (i.e. not the top window). So I might be writing in UltraEdit and want to look at files in D:\Temp, so I summon the Listary toolbar, type Temp and press enter on the correct entry. By default, Listary will open that directory in Directory Opus, but if Directory Opus was opened but not in focus, it won't manage to bring Directory Opus to the front (because in Directory Opus that is two commands - one to open a directory and one to bring Directory Opus to top).

So, a small fix is needed in this situation - Autohotkey script containing those two commands. Create an Autohotkey script:

Run c:\Program Files\GPSoftware\Directory Opus\dopusrt.exe /cmd Go "%1%"
Run c:\Program Files\GPSoftware\Directory Opus\dopusrt.exe /cmd Go LASTACTIVELISTER

Then open Listary Options > General tab and under Default File Manager, set Path to be the path to your AHK script (D:\Documents\apps\AHK\openDirectoryInDirectoryOpus.ahk in my case) and Parameter to %1. See the below screenshot.

Also, turn on Fuzzy Matching - that allows you type out non-contiguous parts of the file/directory name.

Monday, January 20, 2014

Testing synchronous vs asynchronous Dojo 1.9

I have this in a.js:
require(["dojo/_base/xhr"], function(){
  console.log("a");
});

I have this in b.js:
define(["dojo/_base/xhr"], function(){
  console.log("b");
  return {};
});

And I run this (in index.html):
console.log("TESTING Part One");
require([ "a" ], function() {
console.log("c");
});
console.log("TESTING Part Two");
require([ "b" ], function() {
console.log("c");
});

Output 1 - Asynchronous: here is my output with data-dojo-config="async: true"
TESTING Part One
TESTING Part Two
a
c
c
b

Output 2 - Synchronous: here is my output with data-dojo-config=""
TESTING Part One
a
c
TESTING Part Two
b
c

  1. With output 1, why are the "TESTING Part .." strings being output first?
    1. Is it because the two requires in index.html are creating anonymous blocks of code that are being asynchronously?
    2. Is this sneaky way of spinning off threads?
  2. With output 1, why is "b" even being output at all?
    1. From here: http://livedocs.dojotoolkit.org/loader/amd#the-amd-api: "Module creation is lazy and asynchronous, and does not occur immediately when define is called. This means that factory is not executed, and any dependencies of the module will not be resolved, until some running code actually requires the module."
    2. Nothing is actually calling on "b", so why is it executed at all?
  3. With output 2, does this mean that synchronous config turns off this AMD feature: "Module creation is lazy and asynchronous"?

Friday, October 11, 2013

CSS Custom Cursor that works in IE and Chrome

Frustration with CSS cursor.

This works in Chrome, Firefox and IE (8) (although I can't seem to get this snippet working in IE 8 on my blog)

<P style="cursor: url(/path/to/grab.png), url(/path/to/grab.cur),auto;">
   Text.
</P>

Problems I faced getting this to work.

  1. PNG file works fine on Chrome, not in IE.
  2. CUR file works find in IE, but not in Chrome.
  3. Had to download a program to make CUR files. RealWorld Cursor Editor worked.
  4. But Windows always re-sizes cursor files to 32 pixels x 32 pixels. So I had to resize the image in cur format to fit within the top left quadrant of a 32 pixels x 32 pixels image.
  5. Have to put reference to both file formats in the CSS property, and it wouldn't work in Chroms until I put the auto at the end. cursor: url(/path/to/grab.png), url(/path/to/grab.cur),auto;.

Page that helped me with this:

  1. W3Schools demo page for cursors.

Wednesday, September 04, 2013

Load Java Properties file from relative or absolute path

/**
 * Load properties.
 *
 * @param propertiesFile
 *            path to properties file
 * @return filled in properties object
 * @throws IOException
 *             if something goes wrong
 */
private Properties loadProperties(final String propertiesFile)
      throws IOException {
   // Properties object we are going to fill up.
   Properties properties = new Properties();
   // If file exists as an absolute path, load as input stream.
   final Path path = Paths.get(propertiesFile);
   if (Files.exists(path, LinkOption.NOFOLLOW_LINKS)) {
      properties.load(new FileInputStream(propertiesFile));
   } else {
      // Otherwise, use resource as stream.
      properties.load(getClass().getClassLoader().getResourceAsStream(
            propertiesFile));
   }
   return properties;
}

Sunday, March 31, 2013

Nulls and varargs

I needed to work out how you can invoke methods that have varargs when you don't actually have anything to send for that parameter. Below are the lessons I have learned and below that is the JUnit test that proves it. I am using JDK 7.

  1. When a method has a varargs argument, you can completely ignore it and not put anything at all in that place.
  2. A varargs parameter always has a type, and you can send a single value of that type - or an array of that type.
  3. The array can be empty - but your code should be able to deal with that.
  4. The parameter can be null, although Eclipse wants you cast the null - and your code must be prepared to deal with nulls (or you will throw a NullPointerException).
  5. When using mockit.Deencapsulation to invoke a method that accepts varargs, you cannot ignore the parameter; it has to have something there or JMockit will throw an IllegalArgumentException.
  6. mockit.Deencapsulation throws an IllegalArgumentException if you send null (cast or not) in place of the varargs because null isn't enough information for JMockit to work out what type of argument it is.
  7. You can tell mockit.Deencapsulation to send null in place of the varargs by using a X[].class as the parameter (where X is the type expected by varargs) - and your code must be prepared to deal with nulls (or you will throw a NullPointerException). See http://bit.ly/ZMYZuR.

Here is the test.

import static org.junit.Assert.assertNotNull;

import java.nio.file.Paths;

import mockit.Deencapsulation;

import org.junit.Test;
import org.junit.runner.RunWith;
import org.junit.runners.JUnit4;

/**
 * Test var args. What calling a method with varargs, you can totally leave out
 * the vararg parameter, but you cannot use null - unless you cast it. But you
 * also can't use a null (even a casted one) when you are using JMockit
 * {@link Deencapsulation#invoke(Class, String, Object...)}.
 *
 * @author RobertMarkBram
 */
@RunWith(JUnit4.class)
public final class TestVarArgs {

  /**
   * A method with var args.
   *
   * @param first
   *           first path
   * @param more
   *           the rest - may be null
   */
  public void readFiles(final String first, final String... more) {
    if (more == null || more.length == 0 || more[0] == null) {
      assertNotNull(Paths.get(first).toString());
    } else {
      assertNotNull(Paths.get(first, more).toString());
    }
  }

  /**
   * Calling {@link #readFiles(String, String...)} with just one arg should
   * work. Completely ignoring the vararg.
   */
  @Test
  public void callMethodWithOneArg() {
    readFiles("C:/Temp");
  }

  /**
   * Calling {@link #readFiles(String, String...)} with just one arg and an
   * empty string should work.
   */
  @Test
  public void callMethodWithOneArgAndEmptyString() {
    readFiles("C:/Temp", "");
  }

  /**
   * Calling {@link #readFiles(String, String...)} with just one arg and an
   * empty array should work.
   */
  @Test
  public void callMethodWithOneArgAndEmptyArray() {
    String[] empty = {};
    readFiles("C:/Temp", empty);
  }

  /**
   * Calling {@link #readFiles(String, String...)} with just one arg and an
   * array with a blank string should work.
   */
  @Test
  public void callMethodWithOneArgAndArrayWithEmptyString() {
    String[] empty = { "" };
    readFiles("C:/Temp", empty);
  }

  /**
   * Calling {@link #readFiles(String, String...)} with just one arg and a null
   * works, but you have to do a null check on the varargs in case it is null.
   * Plus, Eclipse gives you a warning for not casting null as vararg.
   */
  @Test
  @SuppressWarnings("all")
  public void callMethodWithOneArgAndNull() {
    readFiles("C:/Temp", null);
  }

  /**
   * Calling {@link #readFiles(String, String...)} with just one arg and a null
   * cast to the expected type works, but you have to do a null check on the
   * varargs in case it is null.
   */
  @Test
  public void callMethodWithOneArgAndStringCastNull() {
    readFiles("C:/Temp", (String) null);
  }

  /**
   * Calling {@link #readFiles(String, String...)} with just one arg and a null
   * cast to the expected type works, but you have to do a null check on the
   * varargs in case it is null.
   */
  @Test
  public void callMethodWithOneArgAndCastNull() {
    readFiles("C:/Temp", (String[]) null);
  }

  /**
   * Calling {@link #readFiles(String, String...)} via JMockit with just one
   * arg fails with an {@link IllegalArgumentException} because JMockit
   * requires a valid varargs argument, i.e., not null.
   *
   * @see http://bit.ly/ZMYZuR
   */
  @Test(expected = IllegalArgumentException.class)
  public void callMethodWithOneArgJmockit() {
    Deencapsulation.invoke(this, "readFiles", "C:/Temp");
  }

  /**
   * Calling {@link #readFiles(String, String...)} via JMockit with just one
   * arg fails with an {@link IllegalArgumentException} because JMockit
   * requires a valid varargs argument, i.e., not a single element of the
   * array.
   *
   * @see http://bit.ly/ZMYZuR
   */
  @Test(expected = IllegalArgumentException.class)
  public void callMethodWithOneArgAndEmptyStringJmockit() {
    Deencapsulation.invoke(this, "readFiles", "");
  }

  /**
   * Calling {@link #readFiles(String, String...)} via JMockit with just one
   * arg and an empty array should work.
   */
  @Test
  public void callMethodWithOneArgAndEmptyArrayJmockit() {
    String[] empty = {};
    Deencapsulation.invoke(this, "readFiles", "C:/Temp", empty);
  }

  /**
   * Calling {@link #readFiles(String, String...)} via JMockit with just one
   * arg and an array with a blank string should work.
   */
  @Test
  public void callMethodWithOneArgAndArrayWithEmptyStringJmockit() {
    String[] empty = { "" };
    Deencapsulation.invoke(this, "readFiles", "C:/Temp", empty);
  }

  /**
   * Calling {@link #readFiles(String, String...)} via JMockit with just one
   * arg and a null fails with an {@link IllegalArgumentException} because
   * JMockit requires a valid varargs argument, i.e., not null.
   *
   * @see http://bit.ly/ZMYZuR
   */
  @Test(expected = IllegalArgumentException.class)
  public void callMethodWithOneArgAndNullJmockit() {
    Deencapsulation.invoke(this, "readFiles", "C:/Temp", null);
  }

  /**
   * Calling {@link #readFiles(String, String...)} via JMockit with just one
   * arg and a null cast to the expected type fails with an
   * {@link IllegalArgumentException} because JMockit requires a valid varargs
   * argument, i.e., not null.
   *
   * @see http://bit.ly/ZMYZuR
   */
  @Test(expected = IllegalArgumentException.class)
  public void callMethodWithOneArgAndCastNullJmockit() {
    Deencapsulation.invoke(this, "readFiles", "C:/Temp", (String[]) null);
  }

  /**
   * Calling {@link #readFiles(String, String...)} via JMockit with just one
   * arg and a null cast to the expected type fails with an
   * {@link IllegalArgumentException} because JMockit requires a valid varargs
   * argument, i.e., not null.
   *
   * @see http://bit.ly/ZMYZuR
   */
  @Test(expected = IllegalArgumentException.class)
  public void callMethodWithOneArgAndStringCastNullJmockit() {
    Deencapsulation.invoke(this, "readFiles", "C:/Temp", (String) null);
  }

  /**
   * Calling {@link #readFiles(String, String...)} via JMockit with just one
   * arg and a null cast to the expected type fails with an
   * {@link IllegalArgumentException} because JMockit requires a valid varargs
   * argument, i.e., not null.
   *
   * @see http://bit.ly/ZMYZuR
   */
  public void callMethodWithOneArgAndNullArrayJmockit() {
    Deencapsulation.invoke(this, "readFiles", "C:/Temp", String[].class);
  }
}

Further reading.

Saturday, March 30, 2013

Use ThreadLocal for shared objects that are not thread-safe

In my last post, Just date, no time: comparing java.util.Date with org.joda.time.DateMidnight, I outlined one reason for using Joda Time over java.util date/time classes (like java.util.Date and java.util.GregorianCalendar) was thread safety.

To be honest, thread safety with java.util.Date isn't likely to be a problem - because most of the time a date will be an instance field in a mutable data object rather than a shared utility object that multiple threads will use at the same time. What you should look out for are objects that are likely to be shared (like GregorianCalendar, DecimalFormat and SimpleDateFormat). Any time you think "I should really make this a static constant so that multiple methods can share it", check the Javadocs for that object to see if it is mutable. Mutable objects that are shared may cause race conditions if they are accessed by multiple threads at the same time. For example, the below objects are mutable and commonly used as shared utility objects in a single class or entire application.

  • GregorianCalendar: it has setter/mutator methods that change it's state.
  • DecimalFormat: Javadocs say if multiple threads access a format concurrently, it must be synchronized.
  • SimpleDateFormat: Javadocs say if multiple threads access a format concurrently, it must be synchronized externally.

The easiest way to make the above objects thread-safe is to use java.lang.ThreadLocal. This means that every thread may have one copy of the object. Below is an example of this.

/** Each thread may have once copy of DATE_FORMAT. */
public static final ThreadLocal<SimpleDateFormat> DATE_FORMAT =
      new ThreadLocal<SimpleDateFormat>() {
         @Override
         protected SimpleDateFormat initialValue() {
            return new SimpleDateFormat("yyyy/MM/dd HH:mm:s:S");
         }
      };

/** This method uses a thread local version of the formatter. */
public void outputDate() {
   Date date1 = new Date();
   System.out.println(DATE_FORMAT.get().format(date1));
}

Each thread that executes outputDate() will create its own copy of SimpleDateFormat. It solves synchronization issues because no two threads will ever access the same copy of the object at the same time. If your application has 20 threads, then you will have up to 20 copies of SimpleDateFormat: a thread that never executes outputDate() - or any method that uses DATE_FORMAT.get() - will never create its own SimpleDateFormat.

Use this technique for GregorianCalendar, DecimalFormat and SimpleDateFormat. It is safe for most applications because the cost of one of these objects per thread is not high. It is safe for web applications too. In web apps, you are not meant to create your own threads - and you are not doing that here: the web container is the one creating and managing threads, not you.

When not to use this technique:

  • Don't use this technique for objects that must be singletons within an application.
  • Don't use this technique where you must not have multiple threads accessing the same instance (this should be a singleton or have synchronization).
  • Don't use this technique for objects that are heavy enough to break an application if you have multiple copies in memory at the same time.

Other Ways To Solve Thread Safety Issues

There are many ways to solve issues that arise from sharing the same instance of an object. Below is a brief discussion of the most common techniques I know about.

  1. Avoid sharing altogether by keeping the object local. This means every time you need a Calendar, DecimalFormat or SimpleDateFormat etc, declare and initialise the object within each method that uses it.
    private void outputDate(Date date) {
       SimpleDateFormat formatter = new SimpleDateFormat("yyyy/MM/dd HH:mm:s:S");
       System.out.println("Date is [" + formatter.format(date) + "]");
    }
    No other method or thread will ever share the same instance so you will never have a synchronization problem. But you will have other problems.
    • DRY: Don't Repeat Yourself. If you have more than one method that needs to input or output dates in the same format, they should use the same formatter. If each method has their own formatter (using the same format string) subtle errors may arise when you need to change the format, but forget to make the change to each formatter.
    • Object creation overhead. Let's say your application has to call outputDate() a few million times. Your application will be slower because it is creating a SimpleDateFormat X million times when it should be creating it just once.
  2. Use a single shared object, but synchronize each use of it. For example, see below.
    synchronized (FORMATTER) {
       System.out.println("Date is [" + FORMATTER.format(date) + "]");
    }
    
    For a singleton that has state, you will most likely need to use synchronization. No other method or thread will ever get to use the same object at the same time. But you may have other problems.
    • Choke points. synchronization can make applications slower in two ways: the overhead of maintaining locks and the cost of having multiple threads waiting on the currently locked thread. The first isn't much of a problem, but the second may be. If the actions performed in the synchronized block take a long time, then all the other threads that are waiting on the synchronized resource must wait. Sometimes this is necessary, but it is still worth considering if there are other ways of solving the problem (can you have multiple copies of the synchronized resource?).
    • Deadlocks. This type of error can be very hard to debug. A deadlock arises where two or more threads are each waiting for the other to finish, and therefore neither thread can ever finish.
  3. Having multiple copies of the shared resource. If the problem allows you to have multiple copies of the same resource, this can help you avoid synchronization issues. There a couple of ways to do this.
    • Object pooling. This technique involves having a group (or pool) of shared objects. Whoever needs one of the objects takes it from a the pool and releases it when finished. Multi-threaded applications use thread pools. Databases uses connection pools. Web servers use HTTP connection pools. Apache Commons has a Pool Component. This is a good way to control the number of shared objects you wish to have in use, but will often need tuning to make sure that your application has enough objects in the pool to satisfy demand but not so many objects that they take up too much of your finite resources at once.
    • Thread local storage (the subject of this post) is similar to object pooling in that you have multiple objects. However, instead of having a common pool of objects that a limited number of threads can share at once, under thread local storage, every thread can potentially have it's own copy of the object. A pool may have 4 objects to be shared among 10 threads; with thread local storage, you will have up to 10 objects - once for each thread.

ThreadLocal vs synchronization

One more issue that needs discussion here is when to use ThreadLocal vs synchronization. Either technique will work for GregorianCalendar, DecimalFormat and SimpleDateFormat - but only the former (ThreadLocal) is appropriate. Below is one question you should ask yourself when determining which technique is most appropriate for your situation.

Is it necessary for multiple threads to access the same instance of the share object?

If you must have only one copy of an object, use synchronization. For example, consider a bank account in a banking application that has two transactions occurring at the same time. The account has $20 in it and two people are attempting to withdraw $15 at the same time: only one of these transactions can succeed. Logically speaking, there is only one instance of the $20 balance, so you can only have one copy of the account in your application at once. Use synchronization so that only one transaction occurs at a time; the second will fail because there are insufficient funds.

Just date, no time: comparing java.util.Date with org.joda.time.DateMidnight

In my current application I am dealing with date input; no times are involved. Therefore it is important that in my code, every date has the same time so that they compare correctly. All java.util.Date objects have a time attached, and if you use the default constructor, they will reflect the time at which they were created, down to the millisecond. It means that two dates constructed at different times are not the same, as you can see from the below code.

Date date1 = new Date();
SimpleDateFormat formatter = new SimpleDateFormat("yyyy/MM/dd HH:mm:s:S");
Date date1 = new Date();
try {
   Thread.sleep(1000);
} catch (InterruptedException e) {
   e.printStackTrace();
}
Date date2 = new Date();
System.out.println("date1.compareTo(date2) [" + date1.compareTo(date2) + "]");
System.out.println("date 1: " + formatter.format(date1));
System.out.println("date 2: " + formatter.format(date2));

The output of this code is below.

date1.compareTo(date2) [-1]
date 1: 2013/03/30 19:59:58:470
date 2: 2013/03/30 19:59:59:470

So when dealing with dates in Java, I need to make sure all my dates have the same time. I will show below how you can do this with java.util.Date and compare it with a convenience class in Joda Time called org.joda.time.DateMidnight.

Why Joda Time?

  1. Joda Time is more concise and easier to use than Java's in-built time classes. For example, java.util.Date.getHours() is deprecated and says you should use java.util.Calendar.get(Calendar.HOUR_OF_DAY). Joda Time's base time class - org.joda.time.base.AbstractDateTime - has getHourOfDay().
  2. java.util.Date and java.util.Calendar are not thread-safe. Joda time has org.joda.time.DateMidnight and org.joda.time.DateTime which are thread-safe (or org.joda.time.MutableDateTime if you need a version that can be modified - and thus not thread-safe).
    • What makes them not thread-safe? java.util.Date and java.util.Calendar objects can be changed after they are created: they are mutable; they have setter/mutator methods. Even though these methods are deprecated, they are still there and can still introduce subtle bugs in your code if used.
    • java.util.Date's javadoc says to use java.util.Calendar (which usually means java.util.GregorianCalendar) when you need to change the date/time (and then call getTime() to get a new date object with the modified data). To convert dates to strings or vice versa, use java.text.SimpleDateFormat. Unfortunately, none of these are thread-safe: java.util.Date, java.util.Calendar, java.util.GregorianCalendar and java.text.SimpleDateFormat.
    • So what? For single threaded applications this is not important. But for any application that uses multiple threads, it is very important. If logic from more than one thread changes the state of a single object they each rely on, it may make the results un-predictable. For example: thread 1 is changing a calendar object to be some date in 2000 while thread 2 is changing the same calendar object to be some date in 2013. If those instructions happen to execute at the same time, both threads might end up with a date different to what they are expecting. Any web application is multi-threaded.

Here is my code comparing uses of Java's time with Joda Time.

import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Date;
import java.util.GregorianCalendar;

import org.joda.time.DateMidnight;
import org.joda.time.DateTime;
import org.joda.time.DateTimeConstants;
import org.joda.time.DurationFieldType;
import org.joda.time.format.DateTimeFormat;
import org.joda.time.format.DateTimeFormatter;

public final class TestDates {

   public static void main(String[] args) {
      gregorian();
      joda();
   }

   public static void gregorian() {
      System.out.format("%34s%n", "--- java.util ---");
      SimpleDateFormat formatter = new SimpleDateFormat("yyyy/MM/dd HH:mm:s:S");

      // Default date.
      GregorianCalendar calendar1 = new GregorianCalendar();
      Date date1 = calendar1.getTime();
      System.out.format("%34s %s%n", "Default date", formatter.format(date1));

      // Set date through constructor.
      GregorianCalendar calendar2 =
            new GregorianCalendar(2013, Calendar.APRIL, 30);
      Date date2 = calendar2.getTime();
      System.out.format("%34s %s%n", "Set date through constructor",
            formatter.format(date2));

      // Set date through modifier methods.
      GregorianCalendar calendar3 = new GregorianCalendar();
      calendar3.set(Calendar.YEAR, 2013);
      calendar3.set(Calendar.MONTH, Calendar.APRIL);
      calendar3.set(Calendar.DAY_OF_MONTH, 29);
      calendar3.set(Calendar.HOUR_OF_DAY, 0);
      calendar3.set(Calendar.MINUTE, 0);
      calendar3.set(Calendar.SECOND, 0);
      calendar3.set(Calendar.MILLISECOND, 0);
      Date date3 = calendar3.getTime();
      System.out.format("%34s %s%n", "Set date through modifier methods",
            formatter.format(date3));

      // Parsing a date from a string.
      try {
         Date date4 = formatter.parse("2013/04/29 00:00:0:0");
         System.out.format("%34s %s%n", "Parsing a date from a string",
               formatter.format(date4));
      } catch (ParseException e) {
         System.err.println("Unable to parse date");
         e.printStackTrace();
      }
   }

   public static void joda() {
      System.out.format("%34s%n", "--- org.joda.time ---");
      DateTimeFormatter DATE_FORMAT =
            DateTimeFormat.forPattern("yyyy/MM/dd HH:mm:s:S");

      // Default date.
      DateMidnight date1 = new DateMidnight();
      System.out.format("%34s %s%n", "Default date", DATE_FORMAT.print(date1));

      // Set date through constructor.
      DateMidnight date2 = new DateMidnight(2013, DateTimeConstants.APRIL, 30);
      System.out.format("%34s %s%n", "Set date through constructor",
            DATE_FORMAT.print(date2));

      // Set date based on another date (DateMidnight is immutable, so you
      // cannot change it's state, but it has convenience methods to let you
      // easily make a new date from an existing date.
      DateMidnight date3 = date2.withFieldAdded(DurationFieldType.days(), -1);
      System.out.format("%34s %s%n", "Set date based on another date",
            DATE_FORMAT.print(date3));

      // Parsing a date from a string.
      DateTime date4 = DATE_FORMAT.parseDateTime("2013/04/29 00:00:0:0");
      System.out.format("%34s %s%n", "Parsing a date from a string",
            DATE_FORMAT.print(date4));
   }
}

The output from the code above is here.

                 --- java.util ---
                      Default date 2013/03/30 19:16:56:685
      Set date through constructor 2013/04/30 00:00:0:0
 Set date through modifier methods 2013/04/29 00:00:0:0
      Parsing a date from a string 2013/04/29 00:00:0:0
             --- org.joda.time ---
                      Default date 2013/03/30 00:00:0:0
      Set date through constructor 2013/04/30 00:00:0:0
    Set date based on another date 2013/04/29 00:00:0:0
      Parsing a date from a string 2013/04/29 00:00:0:0

Conclusions.

For dealing with just dates (no times), org.joda.time.DateMidnight is less verbose than using a combination of java.util.Calendar and java.util.Date. You can see from the code examples above, that using java.util involves using a calendar to set the date and then using getTime() to get a java.util.Date. With Joda Time, I can work directly with a DateMidnight object. Although I can change the date on a calendar to get a new java.util.Date, with DateMidnight I can use convenience methods on it to get a new DateMidnight with different state.

Further reading.