Friday, May 14, 2010

Mapping Immutable Value-Objects with Dozer

2 good things happened to me this week (well actually 3, but I will probably blog about the 3rd one later):

The first thing is that I finally managed to convince Dozer to map immutable objects, and the second one is that I found something interesting to blog about ;)

I mentioned in a previous post about Dozer’s lack of support for constructor arguments. In general Dozer is aimed at supporting JavaBean to JavaBean mapping, and other usage scenarios seem to be hard to implement. It turns out that the problem can be solved using design-patterns, and a little bit of trickery.

The first step towards the solution, is introducing the Builder Pattern. Actually a form of the Builder Pattern that introduced by Joshua Bloch at Java One. The pattern solves the problem of too many constructors, too many constructor arguments, and the verbosity of object creation while using setters. The pattern is described in detail here: http://ow.ly/1L2JV.

Let’s suppose we are about to map an Address JavaBean to an Immutable Address object. Here are the Address classes:

public class Coordinate {
 private double longitude;
 private double latitude;
 // getters, setters, c'tors, equals(), hashCode(), toString(), etc...
}
public class Address {
 private String country;
 private String state;
 private String city;
 private String street;
 private String zipcode;
 private Coordinate coordinate;
 // getters, setters, c'tors, equals(), hashCode(), toString(), etc...
}

And here’s the immutable address:

public class ImmutableCoordinate {
 private final double longitude;
 private final double latitude;
 
 private ImmutableCoordinate(Builder builder) {
  this.latitude = builder.latitude;
  this.longitude = builder.longitude;
 }

 public double getLongitude() {
  return longitude;
 }
 
 public double getLatitude() {
  return latitude;
 }
  
 public static class Builder {
  private double longitude;
  private double latitude;
  
  public Builder longitude(double longitude) {
   this.longitude = longitude;
   return this;
  }
  
  public Builder latitude(double latitude) {
   this.latitude = latitude;
   return this;
  }
  
  public ImmutableCoordinate build() {
   return new ImmutableCoordinate(this);
  }
 }
}
public class ImmutableAddress {
 private final String country;
 private final String state;
 private final String city;
 private final String street;
 private final String zipcode;
 private final ImmutableCoordinate coordinate;
 
 private ImmutableAddress(Builder builder) {
  this.country = builder.country;
  this.state = builder.state;
  this.city = builder.city;
  this.street = builder.street;
  this.zipcode = builder.zipcode;
  this.coordinate = builder.coordinate;  
 }

 public String getCountry() {
  return country;
 }
 
 public String getState() {
  return state;
 }
  
 public String getCity() {
  return city;
 }
 
 public String getStreet() {
  return street;
 }
  
 public String getZipcode() {
  return zipcode;
 }
 
 public ImmutableCoordinate getCoordinate() {
  return coordinate;
 }
  
 public static class Builder {
  private String country;
  private String state;
  private String city;
  private String street;
  private String zipcode;
  private ImmutableCoordinate coordinate;
    
  public Builder country(String country) {
   this.country = country;
   return this;
  }

  public Builder state(String state) {
   this.state = state;
   return this;
  }

  public Builder city(String city) {
   this.city = city;
   return this;
  }

  public Builder street(String street) {
   this.street = street;
   return this;
  }

  public Builder zipcode(String zipcode) {
   this.zipcode = zipcode;
   return this;
  }

  public Builder coordinate(ImmutableCoordinate coordinate) {
   this.coordinate = coordinate;
   return this;
  }
  
  public ImmutableCoordinate getCoordinate() {
   return coordinate;
  }

  public ImmutableAddress build() {
   return new ImmutableAddress(this);
  }
 }
}

Now, by we can map our mutable class to the Builder of the immutable class, and throw in a custom DozerConverter where nested properties are involved. Below is the mapping for the Address classes:

<?xml version="1.0" encoding="UTF-8"?>
<mappings xmlns="http://dozer.sourceforge.net"
          xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
          xsi:schemaLocation="http://dozer.sourceforge.net
          http://dozer.sourceforge.net/schema/beanmapping.xsd">

 <configuration>
  <stop-on-errors>true</stop-on-errors>
  <date-format>MM/dd/yyyy HH:mm</date-format>
  <wildcard>true</wildcard>
 </configuration>
 
 <mapping>
  <class-a>location.Coordinate</class-a>
  <class-b>location.ImmutableCoordinate$Builder</class-b>
  
  <field>
   <a set-method="setLongitude">longitude</a>
   <b set-method="longitude">longitude</b>
  </field>
  <field>
   <a set-method="setLatitude">latitude</a>
   <b set-method="latitude">latitude</b>
  </field>
 </mapping>

 <mapping>
  <class-a>location.Address</class-a>
  <class-b>location.ImmutableAddress$Builder</class-b>
  
  <field>
   <a set-method="setCountry">country</a>
   <b set-method="country">country</b>
  </field>
  <field>
   <a set-method="setState">state</a>
   <b set-method="state">state</b>
  </field>
  <field>
   <a set-method="setCity">city</a>
   <b set-method="city">city</b>
  </field>
  <field>
   <a set-method="street">street</a>
   <b set-method="street">street</b>
  </field>
  <field>
   <a set-method="setZipcode">zipcode</a>
   <b set-method="zipcode">zipcode</b>   
  </field>
  <field custom-converter-id="coordConverter">
   <a set-method="setCoordinate">coordinate</a>
   <b set-method="coordinate">coordinate</b>
  </field>
 </mapping>
</mappings>

And the DozerConverter is a fairly straight forward implementation (I actually use Dozer to do its own job…):

public class CoordinateConverter extends DozerConverter {

 private final Mapper mapper;
  
 public CoordinateConverter(Mapper mapper) {
  super(Coordinate.class, ImmutableCoordinate.class);
  this.mapper = mapper;
 } 
 
 @Override
 public Coordinate convertFrom(ImmutableCoordinate source, Coordinate destination) {  
  return mapper.map(source, Coordinate.class);
 }
 
 @Override
 public ImmutableCoordinate convertTo(Coordinate source, ImmutableCoordinate destination) {
  return source == null ? null : mapper.map(source, ImmutableCoordinate.Builder.class).build();
 }
}

Now mapping between the classes is a matter of a single line:

Address address = new Address();
// set set set...
  
ImmutableAddress immutableAddress = mapper.map(address, ImmutableAddress.Builder.class).build();
And it even works in the opposite direction :D

Although this solution is not as clean as it should have been – there’s still some over verbosity, and an obscure need for a getter in some cases, it is still preferable over the piles of code you get when messing with object mapping. This technique may also be easier to sneak into the Dozer code-base than constructor arguments support.

Thursday, April 8, 2010

Sending Emails using Spring-Mail

Some applications are required to send emails. What can I say? These are the things we have to do for money…

The JavaMail API is pretty much boring and a little cumbersome to use. Once again you find yourself fiddling with connection management, exception handling, etc. And once again Spring comes to the rescue :)

Spring-Mail has neat and easy to use email API, including MIME messages support.

Let’s imagine we need to implement “forgot my password” feature. So here goes.
The EmailFacade:

package mail;

public interface EmailFacade {

    public void sendPasswordReminderEmailTemplate(String user, String password, String email);
}
The implementations:
package mail;

import org.springframework.mail.MailSender;
import org.springframework.mail.SimpleMailMessage;
import org.springframework.util.Assert;


class EmailFacadeImpl implements EmailFacade {

    private final MailSender mailSender;
    private final SimpleMailMessage passwordReminderEmailTemplate;


    public EmailFacadeImpl(MailSender mailSender, SimpleMailMessage passwordReminderEmailTemplate) {
        Assert.notNull(mailSender, "mailSender may not be null");
        Assert.notNull(passwordReminderEmailTemplate,
                       "passwordReminderEmailTemplate may not be null");

        this.mailSender = mailSender;
        this.passwordReminderEmailTemplate = passwordReminderEmailTemplate;
    }

    public void sendPasswordReminderEmailTemplate(String user, String password, String email) {
        // Create a thread safe instance of the template message and customize it
        SimpleMailMessage msg = new SimpleMailMessage(passwordReminderEmailTemplate);
        String formatedText = String.format(passwordReminderEmailTemplate.getText(), user, password);
        msg.setText(formatedText);
        msg.setTo(email);
        mailSender.send(msg);
    }
}
And the Spring Configuration:
  <bean id="emailFacade" class="mail.EmailFacadeImpl">
        <constructor-arg>
     <bean class="org.springframework.mail.javamail.JavaMailSenderImpl">
   <property name="host" value="${emailServerURL}"/>
   <property name="username" value="${emailPrincipal}"/>
   <property name="password" value="${emailPassword}"/>
     </bean>
        </constructor-arg>
        <constructor-arg ref="passwordReminderEmailTemplate"/>
  </bean> 
 
  <bean id="passwordReminderEmailTemplate" class="org.springframework.mail.SimpleMailMessage">
    <property name="from" value="me@mycompany.com"/>
    <property name="subject" value="Password Reminder"/>
    <property name="text">
      <!-- Text template to be used with String.format() -->
      <value><![CDATA[Hi %s,
Your password is
%s]]>
      </value>
    </property>
  </bean>
TADA!

For some use cases it would be better to replace the String.format() call with some templating engine such as Velocity. I left it here for brevity.

Thursday, February 18, 2010

Software Craftsmanship

Uncle Bob talks about Software Craftsmanship and agile: http://java.dzone.com/videos/object-mentors-bob-martin.

I couldn't agree more.

In my opinion software development should become a closed guild. Anyone can write code, but we should strive to make quality code, and we should make our occupation a respectable one!

Ignore the rules, and you’re out ;)

We will not ship shit. Well put Bob.

Friday, February 12, 2010

Event Horizon

When working in an agile environment, being able to control parts of the architecture like layers, conventions, etc, is usually desired, while letting the teams make most of the design decisions. Easier said than done. In this model the architect envisions the initial architecture and, communicates the architecture to the team. The architecture evolves over time according to the needs, while the architect shapes it, to keep things simple and “right”.

Keeping track of what’s going on in a large code base is virtually impossible. Even the most skilled developers might miss architecture violations, while performing code reviews for a big chunk of code.

In order to solve this I use a powerful tool called Structure-101 (I call it s101). The s101 client on its own is brilliant for analyzing the code base and defines / communicate the desired architecture. However having to manually check out the latest code, check for new violations, see what has changed and notify the developer, who created new violations, is tedious and time consuming. Luckily s101 comes with a command line utility called S101Headless, which can be integrated into your nightly build. The S101Headless utility allows you to test for new / existing structural violations / increased code complexity, and publish a new snapshot.

The strategy that I use with s101 is as follows. First I analyze the code base, define the architecture diagrams, and extract recommendations for refactoring. Later by integrating s101 into the nightly build, I control the evolution of the architecture. Legacy code bases usually contain many design tangles which are hard to get rid of, and, usually you won’t get the resources for refactoring… Still it is easy to seal the complexity and isolate it from the “happy code”. S101 allows you to break the build only on when new architectural violations show up.

The current version of S101Headless is somewhat awkward to use with Ant, even though it is much better than the previous version. The utility consumes an XML file containing the operations you want executed. But hey, the arguments are usually dynamic, especially in a build environment. The documentation suggests utilizing the echo task in order to write the XML file to disk. While this approach allows you to use the Ant variables, it is makes your XML file less readable. Here’s how I do it:

First you need a template file (s101headless-template.xml):
<?xml version="1.0" encoding="UTF-8"?>
<headless version="1.0">

    <operations>
        <operation type="check-architecture">
            <argument name="output-file" value="@REPORTS_DIR@/arch-violations.csv"/>
            <argument name="onlyNew" value="true"/>
        </operation>

        <operation type="publish">
            <argument name="rpkey" value="c0d3s1ut"/>
        </operation>
    </operations>


    <arguments>
        <argument name="local-project" value="@S101_LOCAL_PROJECT@">
            <override attribute="classpath" value="@CLASSPATH_OVERRIDE@"/>
        </argument>
        <argument name="repository" value="@S101_REPOSITORY@"/>
        <argument name="project" value="@S101_PROJECT@-snapshots"/>
    </arguments>

</headless>
In the Ant build file I use copy with a filter chain to render the XML for the S101Headless utility:
<target name="prepareHeadlessFile" depends="setup_classpath">
                <copy file="s101headless-template.xml" tofile="s101headless.xml" overwrite="true">
                        <filterchain>
                                <replacestring from="@CLASSPATH_OVERRIDE@" to="${my-jars-path}"/>
                                <replacestring from="@REPORTS_DIR@" to="${s101.reports.dir}"/>
                                <replacestring from="@S101_PROJECT@" to="${s101.project.name}"/>
                                <replacestring from="@S101_REPOSITORY@" to="${s101.repository}"/>
                                <replacestring from="@S101_LOCAL_PROJECT@" to="${s101.local.project}"/>
                        </filterchain>
                </copy>
        </target>

        <target name="s101" depends="prepareHeadlessFile">
                <mkdir dir="${s101.reports.dir}"/>
                <java classname="com.headway.assemblies.seaview.headless.S101Headless" fork="true" errorproperty="s101.failure" resultproperty="s101.result.code" maxmemory="512m" dir="${s101.java.home}">
                        <classpath>
                                <pathelement path="${s101.java.home}/structure101-java-b586.jar"/>
                                <pathelement path="${basedir}"/>
                        </classpath>
                        <arg value="${basedir}/s101headless.xml"/>
                </java>
                <!-- fail if there were errors in the S101Headless execution -->
                <condition property="s101.violations.found">
                        <not>
                                <equals arg1="${s101.result.code}" arg2="0" />
                        </not>
                </condition>
                <fail if="s101.violations.found" message="${s101.failure}"/>
        </target>
I leave the Ant classpath and properties setup as an exercise to the reader ;)

As a complementary to the nightly build analysis, s101 also offers an IDE plugin, which allows connects to the structure 101 repository, and can display real time errors / warnings when new violations are detected in the code. IMHO the Eclipse plugin is still in its infancy, and requires some improvements. In the near future (I hope), it will provide a real time, 24/7, protection against evil code :D

BTW, can anyone guess why I called this post “Event Horizon”?