November 15, 2010

Builders to setup Unit test data

Exposing Setter methods or constructors in domain objects for setting up Unit test data should never be done.
Builder pattern is a simple alternate to setup unit test data using reflection without exposing unnecessary setters and constructors in domain objects.

1) Abstract builder:
Create an Abstract builder that will be extended by all domain builder objects.
import java.lang.reflect.Field;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

public class AbstractBuilder<E> {
    private E domain;

    public AbstractBuilder(E domain) {
        this.domain = domain;
    }

    public E build() {
        try {
            List<Field> domainFields = getAllFields(new ArrayList<Field>(), domain.getClass());
            Map<String, Field> builderFieldsMap = index(getAllFields(new ArrayList<Field>(), this.getClass()));
            for (Field domainField : domainFields) {
                Field builderField = builderFieldsMap.get(domainField.getName());
                if (builderField != null) {
                    copyFieldValue(domainField, builderField);
                }
            }
        } catch (Exception e) {
            throw new RuntimeException(e);
        }
        return domain;
    }

    private void copyFieldValue(Field domainField, Field builderField) throws IllegalAccessException {
        domainField.setAccessible(true);
        builderField.setAccessible(true);
        domainField.set(domain, builderField.get(this));
    }

    private Map<String, Field> index(List<Field> allFields) {
        Map<String, Field> map = new HashMap<String, Field>();
        for (Field allField : allFields) {
            map.put(allField.getName(), allField);
        }
        return map;
    }

    public static List<Field> getAllFields(List<Field> fields, Class<?> type) {
        for (Field field : type.getDeclaredFields()) {
            fields.add(field);
        }
        if (type.getSuperclass() != null) {
            fields = getAllFields(fields, type.getSuperclass());
        }
        return fields;
    }

    public E getDomain() {
        return domain;
    }
}

2) Domain builder class:
Consider a domain class Person with 4 attributes (firstName, lastName, gender, dateOfBirth). You should create the domain builder object with same 4 attributes.

public class PersonBuilder extends AbstractBuilder<Person> {
    private String firstName;
    private String lastName;
    private String gender;
    private Date dateOfBirth;

    public PersonBuilder() {
        super(new Person());
    }

    public PersonBuilder withFirstName(String firstName) {
        this.firstName = firstName;
        return this;
    }

    public PersonBuilder withLastName(String lastName) {
        this.lastName = lastName;
        return this;
    }

    public PersonBuilder withGender(String gender) {
        this.gender = gender;
        return this;
    }

    public PersonBuilder withDateOfBirth(Date dateOfBirth) {
        this.dateOfBirth = dateOfBirth;
        return this;
    }
}

3) Using Builders in Unit Tests:

You can use the builder as shown below
Person testPerson = new PersonBuilder().withFirstName("hello").withLastName("World").build();

Tip:
If you are using Intellij IDEA as the IDE, use Builder plugin to generate the "with" methods quickly.

Redeploy application to Weblogic Server through Ant script

The most time consuming task in a Web app development is to redeploy the application into the server for every change and test it.

In Weblogic Workshop IDE, we have an option to redeploy the app into Weblogic server by just right clicking it. But in Intellij Idea, I was not able to find such feature. We spent considerable amount of time to redeploy application using 'Weblogic Console' until we figured out the 'Ant' script to do it.

<project>
<property name="bea.home" value="C:/bea"/>
<property name="wl.home" value="${bea.home}/weblogic92"/>
<property name="wl.domain" value="domainName"/>
<property name="wl.server" value="serverName"/>
<!-- classpath to have weblogic.jar as the first jar -->
<path id="base.path">
<fileset file="${wl.home}/server/lib/weblogic.jar"/>
<fileset dir="${wl.home}/server/lib/">
<include name="**/*.jar"/>
</fileset>
<pathelement path="${java.class.path}/"/>
</path>

<!-- weblogic tasks-->
<taskdef name="wldeploy" classname="weblogic.ant.taskdefs.management.WLDeploy">
<classpath refid="base.path"/>
</taskdef>
<taskdef name="wlserver" classname="weblogic.ant.taskdefs.management.WLServer">
<classpath refid="base.path"/>
</taskdef>

<target name="deployApp">
<wldeploy action="deploy" verbose="true" debug="true"
name="sampleApp" source="z:/app/target/sampleApp.ear"
user="weblogic" password="weblogic"
adminurl="t3://localhost:7001" targets="${wl.server}"/>
</target>

<target name="redeployApp">
<wldeploy action="undeploy" verbose="true" debug="true" name="sampleApp" 
user="weblogic" password="weblogic"
adminurl="t3://localhost:7001" targets="${wl.server}"/>
<wldeploy action="deploy" verbose="true" debug="true"
name="sampleApp" source="z:/app/target/sampleApp.ear"
user="weblogic" password="weblogic"
adminurl="t3://localhost:7001" targets="${wl.server}"/>
</target>
</project>

TIP:
Use SUBST command in Windows to map your project location to a new drive. For eg.,
subst z: d:/venky/projects/utils/sampleApp 

Individual developers in the team can checkout the code to any location but using this SUBST command will help the team to refer the project from same location like z:/src. Even though IDE's use relative path, it is nice to do this as the team can use these kinds of file without any customization.

July 20, 2010

Hibernate @OneToMany annotation filter by Latest date

When there is a @OneToMany relationship between domain objects, a common requirement is to fetch the latest child record based on some date column or a version number column. This can be easily implemented in Hibernate using @Filter annotation and some SQL as shown below.

Consider a case where a Person has more than one Mobile phone and he always uses the latest mobile phone.

Person object has a @OneToMany relationship to MobilePhone object .
@Entity
@Table(name = "PERSON")
@FilterDef(name = Person.LATEST_PHONE_FILTER)
public class Person{
   public static final String LATEST_PHONE_FILTER = "latestPhoneFilter";

   @Column(name = "PERSON_ID")
   private Long id;

   @Column(name = "FIRST_NAME")   
   private String firstName;

   @Column(name = "LAST_NAME")
   private String lastName;

   @OneToMany(mappedBy = "owner", fetch = FetchType.EAGER)
   @Filter(name = LATEST_PHONE_FILTER, condition = "PURCHASE_DATE =
   (select max(M.PURCHASE_DATE) from MOBILE_PHONE M where M.PERSON_ID= PERSON_ID")
   private List<MobilePhone> mobilePhones;
   
   public MobilePhone getLatestMobilePhone(){
      return CollectionsUtil.isEmpty(mobilePhones) ? null: mobilePhones.get(0);
   }
}
@Entity
@Table(name = "MOBILE_PHONE")
public class MobilePhone{    
    ..............
    ..............
    @Column(name = "PURCHASE_DATE")
    private Date purchaseDate;

    @ManyToOne(fetch = FetchType.LAZY)
    @JoinColumn(name = "PERSON_ID")
    private Person owner;
}

If you notice the SQL used in the filter, it has a condition like  M.PERSON_ID= PERSON_ID.
PERSON_ID column without alias name refers to the PERSON tables primary key. Hibernate takes care of giving proper alias name while generating SQL.

This configuration will always fetch only the latest mobile phone to the List of MobilePhone and the getLatestMobilePhone() method can return that object.

May 29, 2010

Recommended Technical Books

Long time since I wrote any blog..
We recently got new technical books for our office library. ThoughtWorkers pitched in with their books recommendation and we ended up getting a great collection of books. I hope these recommended books will help others too.

Title (Sorted Alphabetically)
Author
1
About Face 3: The Essentials Of Interaction Design
Alan Cooper, Robert Reimann, David Cronin
2
Agile Estimating and Planning
Mike Cohn
3
Agile Software Development 2ed- The Cooperative Game
Cockburn
4
Agile Software Development, Principles, Patterns, And Practices
Robert C. Martin
5
Agile Testing: Practical Guide For Testers
Lisa Crispin
6
Bargaining For Advantage: Negotiation Strategies For Reasonable People 2nd Edition
G. Richard Shell
7
Clean Code: A Handbook Of Agile Software Craftsmanship
Robert C. Martin, Michael C. Feathers, Timothy R. Ottinger
8
Clr Via C#: Applied Microsoft.net Programming 2e
Richter J
9
Cocoa Design Patterns
Erik Buck, Donald Yacktman
10
Cocoa Programming Developer's Handbook (developer's Library)
David Chisnall, Scott Anguish, Erik Buck, Donald A. Yacktman
11
Concepts, Techniques, And Models Of Computer Programming
Haridi Seif
12
Concurrent Programming On Windows
Joe Duffy
13
Core Python Programming 2nd Edition
Chun
14
Design Patterns: Elements Of Reusable Object Oriented Software
Gamma
15
Designing Gestural Interfaces: Touchscreens And Interactive Devices
Dan Saffer
16
Designing Interfaces: Patterns For Effective Interaction Design
Jenifer Tidwell
17
Domain-driven Design
Eric Evans
18
Don't Make Me Think: A Common Sense Approach To Web Usability, 2nd Edition
Steve Krug
19
Emotional Design: Why We Love (or Hate) Everyday Things
Donald A. Norman
20
Enterprise Integration Patterns: Designing, Building, And Deploying Messaging Solutions
Gregor Hohpe, Bobby Woolf
21
Essentials Of Programming Languages,3/ed.
Daniel P Friedman
22
Ext Js 3.0 Cookbook
Jorge Ramon
23
Extreme Programming Explained 2nd Edition
Beck
24
Getting Things Done: The Art Of Stress-free Productivity
David Allen
25
Groovy And Grails Recipes (recipes: A Problem-solution Approach)
Bashar Abdul-jawad
26
Groovy Recipes
Scott Davis
27
Growing Object-oriented Software, Guided By Tests (beck Signature)
Steve Freeman, Nat Pryce
28
Gui Bloopers 2.0, Second Edition: Common User Interface Design Don'ts And Dos (interactive Technologies)
Jeff Johnson
29
Handbook Of Usability Testing: How To Plan, Design And Conduct Effective Tests, 2nd Ed
Jeffrey Rubin, Dana Chisnell
30
Head First Ajax
M. Rebecca Riordan
31
Head First Iphone Development
Dan Pilone, Tracey Pilone
32
Head First Javascript
Michael Morrison
33
Head First Object-oriented Analysis & Design
Brett Mclaughlin, Gary Pollice, David West
34
High Performance Web Sites: Essential Knowledge For Front-end Engineers
Steve Souders
35
Implementation Patterns (addison-wesley Signature)
Kent Beck
36
Influence: The Psychology Of Persuasion (collins Business Essentials)
Robert B. Cialdini
37
Introduction To Algorithms 3e
Thomas H Cormen
38
Iphone For Programmers: An App-driven Approach (deitel Developer)
Paul Deitel, Harvey Deitel, Abbey Deitel, Eric Kern, Michael Morgano
39
Iphone Hacks: Pushing The Iphone And Ipod Touch Beyond Their Limits
Damien Stolarz, Adam Stolarz, William Hurley, David Jurick, Jurick David, Stolarz Adam, Stolarz Damien
40
Iphone In Action: Introduction To Web And Sdk Development
Christopher Allen, Shannon Applecline
41
Iphone Sdk Development (the Pragmatic Programmers)
Bill Dudney, Christopher Adamson, Marcel Molina
42
Jasper Reports For Java Developers : Create.design,format,and Export Reports With The Wor
Heffelfinger
43
Javascript Programmer's Reference
Alexei White
44
Jquery Cookbook
Cody Lindley
45
Lean Software Development: An Agile Toolkit
Mary Poppendieck, Tom Poppendieck
46
Learning Ext JS
Shea Frederick, Colin Ramsay, and Steve 'Cutter' Blades
47
Lessons Learned In Software Testing
Bret Pittichord, James Bach, Cem Kaner
48
Made To Stick: Why Some Ideas Survive And Others Die
Dan Heath Chip Heath
49
Maverick!
Ricardo Semler
50
Modular Web Design: Creating Reusable Components For User Experience Design And Documentation
Nathan Curtis
51
Patterns Of Enterprise Application Architecture
Martin Fowler
52
Planning Extreme Programming
Kent Beck, Martin Fowler, Martin Fowler
53
Practical Common Lisp
Peter Seibel
54
Practices Of An Agile Developer
Venkat Subramaniam, Andy Hunt
55
Pragmatic Programmer, The
Andy Hunt, David Thomas
56
Professional Css: Cascading Style Sheets For Web Design
Christopher Schmitt, Mark Trammell, Ethan Marcotte, Todd Dominey, Dunstan Orchard, Todd Dominey
57
Programming F#: A Comprehensive Guide For Writing Simple Code To Solve Complex Problems
Chris Smith, Glen Smith
58
Programming Google App Engine: Build and Run Scalable Web Apps on Google's Infrastructure (Animal Guide)
Dan Sanderso
59
Programming In Objective-c: A Complete Introduction To The Objective-c Language
Kochan Stephen G.
60
Programming In Scala: A Comprehensive Step-by-step Guide
Martin Odersky, Lex Spoon, Bill Venners
61
Pulling Strings With Puppet: Configuration Management Made Easy
James Turnbull
62
Python For Unix And Linux System Administration
Noah Gift, Jeremy Jones
63
Refactoring Improving The Design Of Existing Code
Fowler Martin
64
Restful Webservices
Leonard Richardson, Sam Ruby, David Heinemeier
65
Selfish Gene 30th Indian Edn.
Richard Dawkins
66
Smalltalk Best Practice Patterns
Kent Beck
67
Software Testing: A Craftsman's Approach, Third Edition
Paul C. Jorgensen
68
Structure And Interpretation Of Computer Programs - 2nd Edition (mit Electrical Engineering And Computer Science)
Harold Abelson, Gerald Jay Sussman
69
Succeeding With Agile: Software Development Using Scrum (addison-wesley Signature)
Mike Cohn
70
Test-driven Development By Example
Beck
71
Testing Computer Software, 2nd Edition
Cem Kaner, Hung Quoc Nguyen, Jack Falk
72
Testing Extreme Programming
Lisa Crispin, Ken S. Rosenthal, Tip House
73
The Art Of Innovation
Tom Kelley
74
The Design Of Everyday Things
Donald A. Norman, Don Norman
75
The Knowledge-creating Company (harvard Business Review Classics)
Ikujiro Nonaka
76
The New Turing Omnibus: Sixty-six Excursions In Computer Science
A. K. Dewdney
77
The Psychology Of Computer Programming: Silver Anniversary Edition
Gerald M. Weinberg
78
What Customers Want: Using Outcome-driven Innovation To Create Breakthrough Products And Services
Anthony Ulwick
79
Windows Presentation Foundation Unleashed (wpf)
Adam Nathan, Daniel Lehenbauer
80
Working Effectively With Legacy Code
Feathers