Jun 282013

Here is how to customize how Jackson serializes Joda-Time dates to JSON:

objectMapperFactory.registerModule(new SimpleModule() {
        addSerializer(DateTime.class, new StdSerializer<DateTime>(DateTime.class) {
            public void serialize(DateTime value, JsonGenerator jgen, SerializerProvider provider) throws IOException, JsonGenerationException {

You can use this in combination with JodaModule, just place it after the JodaModule is registered.

Alternatively, if all you need is to write DateTimes in ISO 8061 format instead of as Unix epochs, you can use the following:

objectMapperFactory.registerModule(new JodaModule())

JodaModule registers a custom DateTimeSerializer that takes the setting into account. However, unlike the standard Java Date implementation, SerializationFeature.WRITE_DATE_KEYS_AS_TIMESTAMPS and getSerializationConfig().setDateFormat(myDateFormat) are ignored, so there is no way to fine-tune the serialization.

Ultimately a more elegant solution would be to give JodaModule some additional constructors or setters that allow passing in a DateFormatter that its various helper classes would use.

Jul 312012

Trying to unit test some code that was to run inside Solr, I bumped into this:

Cannot mock/spy class org.apache.solr.core.SolrCore
Mockito cannot mock/spy following:
  - final classes
  - anonymous classes
  - primitive types

Fortunately, there’s a simple solution: PowerMock. After adding the following two annotations to my test class definition (and the requisite Maven dependency declarations), everything just worked. No changes needed to the actual Mockito calls themselves. Sweet.

@PrepareForTest( { SolrCore.class })